repository_name stringclasses 316 values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1 value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1 value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
mapbox/rio-color | rio_color/utils.py | magick_to_rio | python | def magick_to_rio(convert_opts):
ops = []
bands = None
def set_band(x):
global bands
if x.upper() == "RGB":
x = "RGB"
bands = x.upper()
set_band("RGB")
def append_sig(arg):
global bands
args = list(filter(None, re.split("[,x]+", arg)))
if len(args) == 1:
args.append(0.5)
elif len(args) == 2:
args[1] = float(args[1].replace("%", "")) / 100.0
ops.append("sigmoidal {} {} {}".format(bands, *args))
def append_gamma(arg):
global bands
ops.append("gamma {} {}".format(bands, arg))
def append_sat(arg):
args = list(filter(None, re.split("[,x]+", arg)))
# ignore args[0]
# convert to proportion
prop = float(args[1]) / 100
ops.append("saturation {}".format(prop))
nextf = None
for part in convert_opts.strip().split(" "):
if part == "-channel":
nextf = set_band
elif part == "+channel":
set_band("RGB")
nextf = None
elif part == "-sigmoidal-contrast":
nextf = append_sig
elif part == "-gamma":
nextf = append_gamma
elif part == "-modulate":
nextf = append_sat
else:
if nextf:
nextf(part)
nextf = None
return " ".join(ops) | Translate a limited subset of imagemagick convert commands
to rio color operations
Parameters
----------
convert_opts: String, imagemagick convert options
Returns
-------
operations string, ordered rio color operations | train | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/rio_color/utils.py#L30-L91 | [
"def set_band(x):\n global bands\n if x.upper() == \"RGB\":\n x = \"RGB\"\n bands = x.upper()\n",
"def append_sig(arg):\n global bands\n args = list(filter(None, re.split(\"[,x]+\", arg)))\n if len(args) == 1:\n args.append(0.5)\n elif len(args) == 2:\n args[1] = float(ar... | """Color utilities."""
import numpy as np
import re
# The type to be used for all intermediate math
# operations. Should be a float because values will
# be scaled to the range 0..1 for all work.
math_type = np.float64
epsilon = np.finfo(math_type).eps
def to_math_type(arr):
"""Convert an array from native integer dtype range to 0..1
scaling down linearly
"""
max_int = np.iinfo(arr.dtype).max
return arr.astype(math_type) / max_int
def scale_dtype(arr, dtype):
"""Convert an array from 0..1 to dtype, scaling up linearly
"""
max_int = np.iinfo(dtype).max
return (arr * max_int).astype(dtype)
|
mapbox/rio-color | scripts/optimize_color.py | time_string | python | def time_string(seconds):
s = int(round(seconds)) # round to nearest second
h, s = divmod(s, 3600) # get hours and remainder
m, s = divmod(s, 60) # split remainder into minutes and seconds
return "%2i:%02i:%02i" % (h, m, s) | Returns time in seconds as a string formatted HHHH:MM:SS. | train | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/scripts/optimize_color.py#L20-L25 | null | #!/usr/bin/env python
"""Example script"""
from __future__ import division, print_function
import random
import time
from simanneal import Annealer
import click
import numpy as np
import rasterio
from rasterio.plot import reshape_as_image
from rio_color.operations import parse_operations
from rio_color.utils import to_math_type
def progress_report(
curr, best, curr_score, best_score, step, totalsteps, accept, improv, elaps, remain
):
"""Report progress"""
text = """
Current Formula {curr} (hist distance {curr_score})
Best Formula {best} (hist distance {best_score})
Step {step} of {totalsteps}
Acceptance Rate : {accept} %
Improvement Rate: {improv} %
Time {elaps} ( {remain} Remaing)""".format(
**locals()
)
return text
# Plot globals
fig = None
txt = None
imgs = []
class ColorEstimator(Annealer):
"""Optimizes color using simulated annealing"""
keys = "gamma_red,gamma_green,gamma_blue,contrast".split(",")
def __init__(self, source, reference, state=None):
"""Create a new instance"""
self.src = source.copy()
self.ref = reference.copy()
if not state:
params = dict(gamma_red=1.0, gamma_green=1.0, gamma_blue=1.0, contrast=10)
else:
if self._validate(state):
params = state
else:
raise ValueError("invalid state")
super(ColorEstimator, self).__init__(params)
def validate(self):
"""Validate keys."""
# todo validate values bt 0..1
for k in self.keys:
if k not in self.state:
return False
def move(self):
"""Create a state change."""
k = random.choice(self.keys)
multiplier = random.choice((0.95, 1.05))
invalid_key = True
while invalid_key:
# make sure bias doesn't exceed 1.0
if k == "bias":
if self.state[k] > 0.909:
k = random.choice(self.keys)
continue
invalid_key = False
newval = self.state[k] * multiplier
self.state[k] = newval
def cmd(self, state):
"""Get color formula representation of the state."""
ops = (
"gamma r {gamma_red:.2f}, gamma g {gamma_green:.2f}, gamma b {gamma_blue:.2f}, "
"sigmoidal rgb {contrast:.2f} 0.5".format(**state)
)
return ops
def apply_color(self, arr, state):
"""Apply color formula to an array."""
ops = self.cmd(state)
for func in parse_operations(ops):
arr = func(arr)
return arr
def energy(self):
"""Calculate state's energy."""
arr = self.src.copy()
arr = self.apply_color(arr, self.state)
scores = [histogram_distance(self.ref[i], arr[i]) for i in range(3)]
# Important: scale by 100 for readability
return sum(scores) * 100
def to_dict(self):
"""Serialize as a dict."""
return dict(best=self.best_state, current=self.state)
def update(self, step, T, E, acceptance, improvement):
"""Print progress."""
if acceptance is None:
acceptance = 0
if improvement is None:
improvement = 0
if step > 0:
elapsed = time.time() - self.start
remain = (self.steps - step) * (elapsed / step)
# print('Time {} ({} Remaing)'.format(time_string(elapsed), time_string(remain)))
else:
elapsed = 0
remain = 0
curr = self.cmd(self.state)
curr_score = float(E)
best = self.cmd(self.best_state)
best_score = self.best_energy
report = progress_report(
curr,
best,
curr_score,
best_score,
step,
self.steps,
acceptance * 100,
improvement * 100,
time_string(elapsed),
time_string(remain),
)
print(report)
if fig:
imgs[1].set_data(
reshape_as_image(self.apply_color(self.src.copy(), self.state))
)
imgs[2].set_data(
reshape_as_image(self.apply_color(self.src.copy(), self.best_state))
)
if txt:
txt.set_text(report)
fig.canvas.draw()
def histogram_distance(arr1, arr2, bins=None):
""" This function returns the sum of the squared error
Parameters:
two arrays constrained to 0..1
Returns:
sum of the squared error between the histograms
"""
eps = 1e-6
assert arr1.min() > 0 - eps
assert arr1.max() < 1 + eps
assert arr2.min() > 0 - eps
assert arr2.max() < 1 + eps
if not bins:
bins = [x / 10 for x in range(11)]
hist1 = np.histogram(arr1, bins=bins)[0] / arr1.size
hist2 = np.histogram(arr2, bins=bins)[0] / arr2.size
assert abs(hist1.sum() - 1.0) < eps
assert abs(hist2.sum() - 1.0) < eps
sqerr = (hist1 - hist2) ** 2
return sqerr.sum()
def calc_downsample(w, h, target=400):
"""Calculate downsampling value."""
if w > h:
return h / target
elif h >= w:
return w / target
@click.command()
@click.argument("source")
@click.argument("reference")
@click.option("--downsample", "-d", type=int, default=None)
@click.option("--steps", "-s", type=int, default=5000)
@click.option("--plot/--no-plot", default=True)
def main(source, reference, downsample, steps, plot):
"""Given a source image and a reference image,
Find the rio color formula which results in an
output with similar histogram to the reference image.
Uses simulated annealing to determine optimal settings.
Increase the --downsample option to speed things up.
Increase the --steps to get better results (longer runtime).
"""
global fig, txt, imgs
click.echo("Reading source data...", err=True)
with rasterio.open(source) as src:
if downsample is None:
ratio = calc_downsample(src.width, src.height)
else:
ratio = downsample
w = int(src.width // ratio)
h = int(src.height // ratio)
rgb = src.read((1, 2, 3), out_shape=(3, h, w))
orig_rgb = to_math_type(rgb)
click.echo("Reading reference data...", err=True)
with rasterio.open(reference) as ref:
if downsample is None:
ratio = calc_downsample(ref.width, ref.height)
else:
ratio = downsample
w = int(ref.width / ratio)
h = int(ref.height / ratio)
rgb = ref.read((1, 2, 3), out_shape=(3, h, w))
ref_rgb = to_math_type(rgb)
click.echo("Annealing...", err=True)
est = ColorEstimator(orig_rgb, ref_rgb)
if plot:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(20, 10))
fig.suptitle("Color Formula Optimization", fontsize=18, fontweight="bold")
txt = fig.text(0.02, 0.05, "foo", family="monospace", fontsize=16)
type(txt)
axs = (
fig.add_subplot(1, 4, 1),
fig.add_subplot(1, 4, 2),
fig.add_subplot(1, 4, 3),
fig.add_subplot(1, 4, 4),
)
fig.tight_layout()
axs[0].set_title("Source")
axs[1].set_title("Current Formula")
axs[2].set_title("Best Formula")
axs[3].set_title("Reference")
imgs.append(axs[0].imshow(reshape_as_image(est.src)))
imgs.append(axs[1].imshow(reshape_as_image(est.src)))
imgs.append(axs[2].imshow(reshape_as_image(est.src)))
imgs.append(axs[3].imshow(reshape_as_image(est.ref)))
fig.show()
schedule = dict(
tmax=25.0, # Max (starting) temperature
tmin=1e-4, # Min (ending) temperature
steps=steps, # Number of iterations
updates=steps / 20, # Number of updates
)
est.set_schedule(schedule)
est.save_state_on_exit = False
optimal, score = est.anneal()
optimal["energy"] = score
ops = est.cmd(optimal)
click.echo("rio color -j4 {} {} {}".format(source, "/tmp/output.tif", ops))
if __name__ == "__main__":
main()
|
mapbox/rio-color | scripts/optimize_color.py | progress_report | python | def progress_report(
curr, best, curr_score, best_score, step, totalsteps, accept, improv, elaps, remain
):
text = """
Current Formula {curr} (hist distance {curr_score})
Best Formula {best} (hist distance {best_score})
Step {step} of {totalsteps}
Acceptance Rate : {accept} %
Improvement Rate: {improv} %
Time {elaps} ( {remain} Remaing)""".format(
**locals()
)
return text | Report progress | train | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/scripts/optimize_color.py#L28-L41 | null | #!/usr/bin/env python
"""Example script"""
from __future__ import division, print_function
import random
import time
from simanneal import Annealer
import click
import numpy as np
import rasterio
from rasterio.plot import reshape_as_image
from rio_color.operations import parse_operations
from rio_color.utils import to_math_type
def time_string(seconds):
"""Returns time in seconds as a string formatted HHHH:MM:SS."""
s = int(round(seconds)) # round to nearest second
h, s = divmod(s, 3600) # get hours and remainder
m, s = divmod(s, 60) # split remainder into minutes and seconds
return "%2i:%02i:%02i" % (h, m, s)
# Plot globals
fig = None
txt = None
imgs = []
class ColorEstimator(Annealer):
"""Optimizes color using simulated annealing"""
keys = "gamma_red,gamma_green,gamma_blue,contrast".split(",")
def __init__(self, source, reference, state=None):
"""Create a new instance"""
self.src = source.copy()
self.ref = reference.copy()
if not state:
params = dict(gamma_red=1.0, gamma_green=1.0, gamma_blue=1.0, contrast=10)
else:
if self._validate(state):
params = state
else:
raise ValueError("invalid state")
super(ColorEstimator, self).__init__(params)
def validate(self):
"""Validate keys."""
# todo validate values bt 0..1
for k in self.keys:
if k not in self.state:
return False
def move(self):
"""Create a state change."""
k = random.choice(self.keys)
multiplier = random.choice((0.95, 1.05))
invalid_key = True
while invalid_key:
# make sure bias doesn't exceed 1.0
if k == "bias":
if self.state[k] > 0.909:
k = random.choice(self.keys)
continue
invalid_key = False
newval = self.state[k] * multiplier
self.state[k] = newval
def cmd(self, state):
"""Get color formula representation of the state."""
ops = (
"gamma r {gamma_red:.2f}, gamma g {gamma_green:.2f}, gamma b {gamma_blue:.2f}, "
"sigmoidal rgb {contrast:.2f} 0.5".format(**state)
)
return ops
def apply_color(self, arr, state):
"""Apply color formula to an array."""
ops = self.cmd(state)
for func in parse_operations(ops):
arr = func(arr)
return arr
def energy(self):
"""Calculate state's energy."""
arr = self.src.copy()
arr = self.apply_color(arr, self.state)
scores = [histogram_distance(self.ref[i], arr[i]) for i in range(3)]
# Important: scale by 100 for readability
return sum(scores) * 100
def to_dict(self):
"""Serialize as a dict."""
return dict(best=self.best_state, current=self.state)
def update(self, step, T, E, acceptance, improvement):
"""Print progress."""
if acceptance is None:
acceptance = 0
if improvement is None:
improvement = 0
if step > 0:
elapsed = time.time() - self.start
remain = (self.steps - step) * (elapsed / step)
# print('Time {} ({} Remaing)'.format(time_string(elapsed), time_string(remain)))
else:
elapsed = 0
remain = 0
curr = self.cmd(self.state)
curr_score = float(E)
best = self.cmd(self.best_state)
best_score = self.best_energy
report = progress_report(
curr,
best,
curr_score,
best_score,
step,
self.steps,
acceptance * 100,
improvement * 100,
time_string(elapsed),
time_string(remain),
)
print(report)
if fig:
imgs[1].set_data(
reshape_as_image(self.apply_color(self.src.copy(), self.state))
)
imgs[2].set_data(
reshape_as_image(self.apply_color(self.src.copy(), self.best_state))
)
if txt:
txt.set_text(report)
fig.canvas.draw()
def histogram_distance(arr1, arr2, bins=None):
""" This function returns the sum of the squared error
Parameters:
two arrays constrained to 0..1
Returns:
sum of the squared error between the histograms
"""
eps = 1e-6
assert arr1.min() > 0 - eps
assert arr1.max() < 1 + eps
assert arr2.min() > 0 - eps
assert arr2.max() < 1 + eps
if not bins:
bins = [x / 10 for x in range(11)]
hist1 = np.histogram(arr1, bins=bins)[0] / arr1.size
hist2 = np.histogram(arr2, bins=bins)[0] / arr2.size
assert abs(hist1.sum() - 1.0) < eps
assert abs(hist2.sum() - 1.0) < eps
sqerr = (hist1 - hist2) ** 2
return sqerr.sum()
def calc_downsample(w, h, target=400):
"""Calculate downsampling value."""
if w > h:
return h / target
elif h >= w:
return w / target
@click.command()
@click.argument("source")
@click.argument("reference")
@click.option("--downsample", "-d", type=int, default=None)
@click.option("--steps", "-s", type=int, default=5000)
@click.option("--plot/--no-plot", default=True)
def main(source, reference, downsample, steps, plot):
"""Given a source image and a reference image,
Find the rio color formula which results in an
output with similar histogram to the reference image.
Uses simulated annealing to determine optimal settings.
Increase the --downsample option to speed things up.
Increase the --steps to get better results (longer runtime).
"""
global fig, txt, imgs
click.echo("Reading source data...", err=True)
with rasterio.open(source) as src:
if downsample is None:
ratio = calc_downsample(src.width, src.height)
else:
ratio = downsample
w = int(src.width // ratio)
h = int(src.height // ratio)
rgb = src.read((1, 2, 3), out_shape=(3, h, w))
orig_rgb = to_math_type(rgb)
click.echo("Reading reference data...", err=True)
with rasterio.open(reference) as ref:
if downsample is None:
ratio = calc_downsample(ref.width, ref.height)
else:
ratio = downsample
w = int(ref.width / ratio)
h = int(ref.height / ratio)
rgb = ref.read((1, 2, 3), out_shape=(3, h, w))
ref_rgb = to_math_type(rgb)
click.echo("Annealing...", err=True)
est = ColorEstimator(orig_rgb, ref_rgb)
if plot:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(20, 10))
fig.suptitle("Color Formula Optimization", fontsize=18, fontweight="bold")
txt = fig.text(0.02, 0.05, "foo", family="monospace", fontsize=16)
type(txt)
axs = (
fig.add_subplot(1, 4, 1),
fig.add_subplot(1, 4, 2),
fig.add_subplot(1, 4, 3),
fig.add_subplot(1, 4, 4),
)
fig.tight_layout()
axs[0].set_title("Source")
axs[1].set_title("Current Formula")
axs[2].set_title("Best Formula")
axs[3].set_title("Reference")
imgs.append(axs[0].imshow(reshape_as_image(est.src)))
imgs.append(axs[1].imshow(reshape_as_image(est.src)))
imgs.append(axs[2].imshow(reshape_as_image(est.src)))
imgs.append(axs[3].imshow(reshape_as_image(est.ref)))
fig.show()
schedule = dict(
tmax=25.0, # Max (starting) temperature
tmin=1e-4, # Min (ending) temperature
steps=steps, # Number of iterations
updates=steps / 20, # Number of updates
)
est.set_schedule(schedule)
est.save_state_on_exit = False
optimal, score = est.anneal()
optimal["energy"] = score
ops = est.cmd(optimal)
click.echo("rio color -j4 {} {} {}".format(source, "/tmp/output.tif", ops))
if __name__ == "__main__":
main()
|
mapbox/rio-color | scripts/optimize_color.py | histogram_distance | python | def histogram_distance(arr1, arr2, bins=None):
eps = 1e-6
assert arr1.min() > 0 - eps
assert arr1.max() < 1 + eps
assert arr2.min() > 0 - eps
assert arr2.max() < 1 + eps
if not bins:
bins = [x / 10 for x in range(11)]
hist1 = np.histogram(arr1, bins=bins)[0] / arr1.size
hist2 = np.histogram(arr2, bins=bins)[0] / arr2.size
assert abs(hist1.sum() - 1.0) < eps
assert abs(hist2.sum() - 1.0) < eps
sqerr = (hist1 - hist2) ** 2
return sqerr.sum() | This function returns the sum of the squared error
Parameters:
two arrays constrained to 0..1
Returns:
sum of the squared error between the histograms | train | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/scripts/optimize_color.py#L168-L191 | null | #!/usr/bin/env python
"""Example script"""
from __future__ import division, print_function
import random
import time
from simanneal import Annealer
import click
import numpy as np
import rasterio
from rasterio.plot import reshape_as_image
from rio_color.operations import parse_operations
from rio_color.utils import to_math_type
def time_string(seconds):
"""Returns time in seconds as a string formatted HHHH:MM:SS."""
s = int(round(seconds)) # round to nearest second
h, s = divmod(s, 3600) # get hours and remainder
m, s = divmod(s, 60) # split remainder into minutes and seconds
return "%2i:%02i:%02i" % (h, m, s)
def progress_report(
curr, best, curr_score, best_score, step, totalsteps, accept, improv, elaps, remain
):
"""Report progress"""
text = """
Current Formula {curr} (hist distance {curr_score})
Best Formula {best} (hist distance {best_score})
Step {step} of {totalsteps}
Acceptance Rate : {accept} %
Improvement Rate: {improv} %
Time {elaps} ( {remain} Remaing)""".format(
**locals()
)
return text
# Plot globals
fig = None
txt = None
imgs = []
class ColorEstimator(Annealer):
"""Optimizes color using simulated annealing"""
keys = "gamma_red,gamma_green,gamma_blue,contrast".split(",")
def __init__(self, source, reference, state=None):
"""Create a new instance"""
self.src = source.copy()
self.ref = reference.copy()
if not state:
params = dict(gamma_red=1.0, gamma_green=1.0, gamma_blue=1.0, contrast=10)
else:
if self._validate(state):
params = state
else:
raise ValueError("invalid state")
super(ColorEstimator, self).__init__(params)
def validate(self):
"""Validate keys."""
# todo validate values bt 0..1
for k in self.keys:
if k not in self.state:
return False
def move(self):
"""Create a state change."""
k = random.choice(self.keys)
multiplier = random.choice((0.95, 1.05))
invalid_key = True
while invalid_key:
# make sure bias doesn't exceed 1.0
if k == "bias":
if self.state[k] > 0.909:
k = random.choice(self.keys)
continue
invalid_key = False
newval = self.state[k] * multiplier
self.state[k] = newval
def cmd(self, state):
"""Get color formula representation of the state."""
ops = (
"gamma r {gamma_red:.2f}, gamma g {gamma_green:.2f}, gamma b {gamma_blue:.2f}, "
"sigmoidal rgb {contrast:.2f} 0.5".format(**state)
)
return ops
def apply_color(self, arr, state):
"""Apply color formula to an array."""
ops = self.cmd(state)
for func in parse_operations(ops):
arr = func(arr)
return arr
def energy(self):
"""Calculate state's energy."""
arr = self.src.copy()
arr = self.apply_color(arr, self.state)
scores = [histogram_distance(self.ref[i], arr[i]) for i in range(3)]
# Important: scale by 100 for readability
return sum(scores) * 100
def to_dict(self):
"""Serialize as a dict."""
return dict(best=self.best_state, current=self.state)
def update(self, step, T, E, acceptance, improvement):
"""Print progress."""
if acceptance is None:
acceptance = 0
if improvement is None:
improvement = 0
if step > 0:
elapsed = time.time() - self.start
remain = (self.steps - step) * (elapsed / step)
# print('Time {} ({} Remaing)'.format(time_string(elapsed), time_string(remain)))
else:
elapsed = 0
remain = 0
curr = self.cmd(self.state)
curr_score = float(E)
best = self.cmd(self.best_state)
best_score = self.best_energy
report = progress_report(
curr,
best,
curr_score,
best_score,
step,
self.steps,
acceptance * 100,
improvement * 100,
time_string(elapsed),
time_string(remain),
)
print(report)
if fig:
imgs[1].set_data(
reshape_as_image(self.apply_color(self.src.copy(), self.state))
)
imgs[2].set_data(
reshape_as_image(self.apply_color(self.src.copy(), self.best_state))
)
if txt:
txt.set_text(report)
fig.canvas.draw()
def calc_downsample(w, h, target=400):
"""Calculate downsampling value."""
if w > h:
return h / target
elif h >= w:
return w / target
@click.command()
@click.argument("source")
@click.argument("reference")
@click.option("--downsample", "-d", type=int, default=None)
@click.option("--steps", "-s", type=int, default=5000)
@click.option("--plot/--no-plot", default=True)
def main(source, reference, downsample, steps, plot):
"""Given a source image and a reference image,
Find the rio color formula which results in an
output with similar histogram to the reference image.
Uses simulated annealing to determine optimal settings.
Increase the --downsample option to speed things up.
Increase the --steps to get better results (longer runtime).
"""
global fig, txt, imgs
click.echo("Reading source data...", err=True)
with rasterio.open(source) as src:
if downsample is None:
ratio = calc_downsample(src.width, src.height)
else:
ratio = downsample
w = int(src.width // ratio)
h = int(src.height // ratio)
rgb = src.read((1, 2, 3), out_shape=(3, h, w))
orig_rgb = to_math_type(rgb)
click.echo("Reading reference data...", err=True)
with rasterio.open(reference) as ref:
if downsample is None:
ratio = calc_downsample(ref.width, ref.height)
else:
ratio = downsample
w = int(ref.width / ratio)
h = int(ref.height / ratio)
rgb = ref.read((1, 2, 3), out_shape=(3, h, w))
ref_rgb = to_math_type(rgb)
click.echo("Annealing...", err=True)
est = ColorEstimator(orig_rgb, ref_rgb)
if plot:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(20, 10))
fig.suptitle("Color Formula Optimization", fontsize=18, fontweight="bold")
txt = fig.text(0.02, 0.05, "foo", family="monospace", fontsize=16)
type(txt)
axs = (
fig.add_subplot(1, 4, 1),
fig.add_subplot(1, 4, 2),
fig.add_subplot(1, 4, 3),
fig.add_subplot(1, 4, 4),
)
fig.tight_layout()
axs[0].set_title("Source")
axs[1].set_title("Current Formula")
axs[2].set_title("Best Formula")
axs[3].set_title("Reference")
imgs.append(axs[0].imshow(reshape_as_image(est.src)))
imgs.append(axs[1].imshow(reshape_as_image(est.src)))
imgs.append(axs[2].imshow(reshape_as_image(est.src)))
imgs.append(axs[3].imshow(reshape_as_image(est.ref)))
fig.show()
schedule = dict(
tmax=25.0, # Max (starting) temperature
tmin=1e-4, # Min (ending) temperature
steps=steps, # Number of iterations
updates=steps / 20, # Number of updates
)
est.set_schedule(schedule)
est.save_state_on_exit = False
optimal, score = est.anneal()
optimal["energy"] = score
ops = est.cmd(optimal)
click.echo("rio color -j4 {} {} {}".format(source, "/tmp/output.tif", ops))
if __name__ == "__main__":
main()
|
mapbox/rio-color | scripts/optimize_color.py | calc_downsample | python | def calc_downsample(w, h, target=400):
if w > h:
return h / target
elif h >= w:
return w / target | Calculate downsampling value. | train | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/scripts/optimize_color.py#L194-L199 | null | #!/usr/bin/env python
"""Example script"""
from __future__ import division, print_function
import random
import time
from simanneal import Annealer
import click
import numpy as np
import rasterio
from rasterio.plot import reshape_as_image
from rio_color.operations import parse_operations
from rio_color.utils import to_math_type
def time_string(seconds):
"""Returns time in seconds as a string formatted HHHH:MM:SS."""
s = int(round(seconds)) # round to nearest second
h, s = divmod(s, 3600) # get hours and remainder
m, s = divmod(s, 60) # split remainder into minutes and seconds
return "%2i:%02i:%02i" % (h, m, s)
def progress_report(
curr, best, curr_score, best_score, step, totalsteps, accept, improv, elaps, remain
):
"""Report progress"""
text = """
Current Formula {curr} (hist distance {curr_score})
Best Formula {best} (hist distance {best_score})
Step {step} of {totalsteps}
Acceptance Rate : {accept} %
Improvement Rate: {improv} %
Time {elaps} ( {remain} Remaing)""".format(
**locals()
)
return text
# Plot globals
fig = None
txt = None
imgs = []
class ColorEstimator(Annealer):
"""Optimizes color using simulated annealing"""
keys = "gamma_red,gamma_green,gamma_blue,contrast".split(",")
def __init__(self, source, reference, state=None):
"""Create a new instance"""
self.src = source.copy()
self.ref = reference.copy()
if not state:
params = dict(gamma_red=1.0, gamma_green=1.0, gamma_blue=1.0, contrast=10)
else:
if self._validate(state):
params = state
else:
raise ValueError("invalid state")
super(ColorEstimator, self).__init__(params)
def validate(self):
"""Validate keys."""
# todo validate values bt 0..1
for k in self.keys:
if k not in self.state:
return False
def move(self):
"""Create a state change."""
k = random.choice(self.keys)
multiplier = random.choice((0.95, 1.05))
invalid_key = True
while invalid_key:
# make sure bias doesn't exceed 1.0
if k == "bias":
if self.state[k] > 0.909:
k = random.choice(self.keys)
continue
invalid_key = False
newval = self.state[k] * multiplier
self.state[k] = newval
def cmd(self, state):
"""Get color formula representation of the state."""
ops = (
"gamma r {gamma_red:.2f}, gamma g {gamma_green:.2f}, gamma b {gamma_blue:.2f}, "
"sigmoidal rgb {contrast:.2f} 0.5".format(**state)
)
return ops
def apply_color(self, arr, state):
"""Apply color formula to an array."""
ops = self.cmd(state)
for func in parse_operations(ops):
arr = func(arr)
return arr
def energy(self):
"""Calculate state's energy."""
arr = self.src.copy()
arr = self.apply_color(arr, self.state)
scores = [histogram_distance(self.ref[i], arr[i]) for i in range(3)]
# Important: scale by 100 for readability
return sum(scores) * 100
def to_dict(self):
"""Serialize as a dict."""
return dict(best=self.best_state, current=self.state)
def update(self, step, T, E, acceptance, improvement):
"""Print progress."""
if acceptance is None:
acceptance = 0
if improvement is None:
improvement = 0
if step > 0:
elapsed = time.time() - self.start
remain = (self.steps - step) * (elapsed / step)
# print('Time {} ({} Remaing)'.format(time_string(elapsed), time_string(remain)))
else:
elapsed = 0
remain = 0
curr = self.cmd(self.state)
curr_score = float(E)
best = self.cmd(self.best_state)
best_score = self.best_energy
report = progress_report(
curr,
best,
curr_score,
best_score,
step,
self.steps,
acceptance * 100,
improvement * 100,
time_string(elapsed),
time_string(remain),
)
print(report)
if fig:
imgs[1].set_data(
reshape_as_image(self.apply_color(self.src.copy(), self.state))
)
imgs[2].set_data(
reshape_as_image(self.apply_color(self.src.copy(), self.best_state))
)
if txt:
txt.set_text(report)
fig.canvas.draw()
def histogram_distance(arr1, arr2, bins=None):
""" This function returns the sum of the squared error
Parameters:
two arrays constrained to 0..1
Returns:
sum of the squared error between the histograms
"""
eps = 1e-6
assert arr1.min() > 0 - eps
assert arr1.max() < 1 + eps
assert arr2.min() > 0 - eps
assert arr2.max() < 1 + eps
if not bins:
bins = [x / 10 for x in range(11)]
hist1 = np.histogram(arr1, bins=bins)[0] / arr1.size
hist2 = np.histogram(arr2, bins=bins)[0] / arr2.size
assert abs(hist1.sum() - 1.0) < eps
assert abs(hist2.sum() - 1.0) < eps
sqerr = (hist1 - hist2) ** 2
return sqerr.sum()
@click.command()
@click.argument("source")
@click.argument("reference")
@click.option("--downsample", "-d", type=int, default=None)
@click.option("--steps", "-s", type=int, default=5000)
@click.option("--plot/--no-plot", default=True)
def main(source, reference, downsample, steps, plot):
"""Given a source image and a reference image,
Find the rio color formula which results in an
output with similar histogram to the reference image.
Uses simulated annealing to determine optimal settings.
Increase the --downsample option to speed things up.
Increase the --steps to get better results (longer runtime).
"""
global fig, txt, imgs
click.echo("Reading source data...", err=True)
with rasterio.open(source) as src:
if downsample is None:
ratio = calc_downsample(src.width, src.height)
else:
ratio = downsample
w = int(src.width // ratio)
h = int(src.height // ratio)
rgb = src.read((1, 2, 3), out_shape=(3, h, w))
orig_rgb = to_math_type(rgb)
click.echo("Reading reference data...", err=True)
with rasterio.open(reference) as ref:
if downsample is None:
ratio = calc_downsample(ref.width, ref.height)
else:
ratio = downsample
w = int(ref.width / ratio)
h = int(ref.height / ratio)
rgb = ref.read((1, 2, 3), out_shape=(3, h, w))
ref_rgb = to_math_type(rgb)
click.echo("Annealing...", err=True)
est = ColorEstimator(orig_rgb, ref_rgb)
if plot:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(20, 10))
fig.suptitle("Color Formula Optimization", fontsize=18, fontweight="bold")
txt = fig.text(0.02, 0.05, "foo", family="monospace", fontsize=16)
type(txt)
axs = (
fig.add_subplot(1, 4, 1),
fig.add_subplot(1, 4, 2),
fig.add_subplot(1, 4, 3),
fig.add_subplot(1, 4, 4),
)
fig.tight_layout()
axs[0].set_title("Source")
axs[1].set_title("Current Formula")
axs[2].set_title("Best Formula")
axs[3].set_title("Reference")
imgs.append(axs[0].imshow(reshape_as_image(est.src)))
imgs.append(axs[1].imshow(reshape_as_image(est.src)))
imgs.append(axs[2].imshow(reshape_as_image(est.src)))
imgs.append(axs[3].imshow(reshape_as_image(est.ref)))
fig.show()
schedule = dict(
tmax=25.0, # Max (starting) temperature
tmin=1e-4, # Min (ending) temperature
steps=steps, # Number of iterations
updates=steps / 20, # Number of updates
)
est.set_schedule(schedule)
est.save_state_on_exit = False
optimal, score = est.anneal()
optimal["energy"] = score
ops = est.cmd(optimal)
click.echo("rio color -j4 {} {} {}".format(source, "/tmp/output.tif", ops))
if __name__ == "__main__":
main()
|
mapbox/rio-color | scripts/optimize_color.py | main | python | def main(source, reference, downsample, steps, plot):
global fig, txt, imgs
click.echo("Reading source data...", err=True)
with rasterio.open(source) as src:
if downsample is None:
ratio = calc_downsample(src.width, src.height)
else:
ratio = downsample
w = int(src.width // ratio)
h = int(src.height // ratio)
rgb = src.read((1, 2, 3), out_shape=(3, h, w))
orig_rgb = to_math_type(rgb)
click.echo("Reading reference data...", err=True)
with rasterio.open(reference) as ref:
if downsample is None:
ratio = calc_downsample(ref.width, ref.height)
else:
ratio = downsample
w = int(ref.width / ratio)
h = int(ref.height / ratio)
rgb = ref.read((1, 2, 3), out_shape=(3, h, w))
ref_rgb = to_math_type(rgb)
click.echo("Annealing...", err=True)
est = ColorEstimator(orig_rgb, ref_rgb)
if plot:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(20, 10))
fig.suptitle("Color Formula Optimization", fontsize=18, fontweight="bold")
txt = fig.text(0.02, 0.05, "foo", family="monospace", fontsize=16)
type(txt)
axs = (
fig.add_subplot(1, 4, 1),
fig.add_subplot(1, 4, 2),
fig.add_subplot(1, 4, 3),
fig.add_subplot(1, 4, 4),
)
fig.tight_layout()
axs[0].set_title("Source")
axs[1].set_title("Current Formula")
axs[2].set_title("Best Formula")
axs[3].set_title("Reference")
imgs.append(axs[0].imshow(reshape_as_image(est.src)))
imgs.append(axs[1].imshow(reshape_as_image(est.src)))
imgs.append(axs[2].imshow(reshape_as_image(est.src)))
imgs.append(axs[3].imshow(reshape_as_image(est.ref)))
fig.show()
schedule = dict(
tmax=25.0, # Max (starting) temperature
tmin=1e-4, # Min (ending) temperature
steps=steps, # Number of iterations
updates=steps / 20, # Number of updates
)
est.set_schedule(schedule)
est.save_state_on_exit = False
optimal, score = est.anneal()
optimal["energy"] = score
ops = est.cmd(optimal)
click.echo("rio color -j4 {} {} {}".format(source, "/tmp/output.tif", ops)) | Given a source image and a reference image,
Find the rio color formula which results in an
output with similar histogram to the reference image.
Uses simulated annealing to determine optimal settings.
Increase the --downsample option to speed things up.
Increase the --steps to get better results (longer runtime). | train | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/scripts/optimize_color.py#L208-L281 | [
"def to_math_type(arr):\n \"\"\"Convert an array from native integer dtype range to 0..1\n scaling down linearly\n \"\"\"\n max_int = np.iinfo(arr.dtype).max\n return arr.astype(math_type) / max_int\n",
"def calc_downsample(w, h, target=400):\n \"\"\"Calculate downsampling value.\"\"\"\n if w... | #!/usr/bin/env python
"""Example script"""
from __future__ import division, print_function
import random
import time
from simanneal import Annealer
import click
import numpy as np
import rasterio
from rasterio.plot import reshape_as_image
from rio_color.operations import parse_operations
from rio_color.utils import to_math_type
def time_string(seconds):
"""Returns time in seconds as a string formatted HHHH:MM:SS."""
s = int(round(seconds)) # round to nearest second
h, s = divmod(s, 3600) # get hours and remainder
m, s = divmod(s, 60) # split remainder into minutes and seconds
return "%2i:%02i:%02i" % (h, m, s)
def progress_report(
curr, best, curr_score, best_score, step, totalsteps, accept, improv, elaps, remain
):
"""Report progress"""
text = """
Current Formula {curr} (hist distance {curr_score})
Best Formula {best} (hist distance {best_score})
Step {step} of {totalsteps}
Acceptance Rate : {accept} %
Improvement Rate: {improv} %
Time {elaps} ( {remain} Remaing)""".format(
**locals()
)
return text
# Plot globals
fig = None
txt = None
imgs = []
class ColorEstimator(Annealer):
"""Optimizes color using simulated annealing"""
keys = "gamma_red,gamma_green,gamma_blue,contrast".split(",")
def __init__(self, source, reference, state=None):
"""Create a new instance"""
self.src = source.copy()
self.ref = reference.copy()
if not state:
params = dict(gamma_red=1.0, gamma_green=1.0, gamma_blue=1.0, contrast=10)
else:
if self._validate(state):
params = state
else:
raise ValueError("invalid state")
super(ColorEstimator, self).__init__(params)
def validate(self):
"""Validate keys."""
# todo validate values bt 0..1
for k in self.keys:
if k not in self.state:
return False
def move(self):
"""Create a state change."""
k = random.choice(self.keys)
multiplier = random.choice((0.95, 1.05))
invalid_key = True
while invalid_key:
# make sure bias doesn't exceed 1.0
if k == "bias":
if self.state[k] > 0.909:
k = random.choice(self.keys)
continue
invalid_key = False
newval = self.state[k] * multiplier
self.state[k] = newval
def cmd(self, state):
"""Get color formula representation of the state."""
ops = (
"gamma r {gamma_red:.2f}, gamma g {gamma_green:.2f}, gamma b {gamma_blue:.2f}, "
"sigmoidal rgb {contrast:.2f} 0.5".format(**state)
)
return ops
def apply_color(self, arr, state):
"""Apply color formula to an array."""
ops = self.cmd(state)
for func in parse_operations(ops):
arr = func(arr)
return arr
def energy(self):
"""Calculate state's energy."""
arr = self.src.copy()
arr = self.apply_color(arr, self.state)
scores = [histogram_distance(self.ref[i], arr[i]) for i in range(3)]
# Important: scale by 100 for readability
return sum(scores) * 100
def to_dict(self):
"""Serialize as a dict."""
return dict(best=self.best_state, current=self.state)
def update(self, step, T, E, acceptance, improvement):
"""Print progress."""
if acceptance is None:
acceptance = 0
if improvement is None:
improvement = 0
if step > 0:
elapsed = time.time() - self.start
remain = (self.steps - step) * (elapsed / step)
# print('Time {} ({} Remaing)'.format(time_string(elapsed), time_string(remain)))
else:
elapsed = 0
remain = 0
curr = self.cmd(self.state)
curr_score = float(E)
best = self.cmd(self.best_state)
best_score = self.best_energy
report = progress_report(
curr,
best,
curr_score,
best_score,
step,
self.steps,
acceptance * 100,
improvement * 100,
time_string(elapsed),
time_string(remain),
)
print(report)
if fig:
imgs[1].set_data(
reshape_as_image(self.apply_color(self.src.copy(), self.state))
)
imgs[2].set_data(
reshape_as_image(self.apply_color(self.src.copy(), self.best_state))
)
if txt:
txt.set_text(report)
fig.canvas.draw()
def histogram_distance(arr1, arr2, bins=None):
""" This function returns the sum of the squared error
Parameters:
two arrays constrained to 0..1
Returns:
sum of the squared error between the histograms
"""
eps = 1e-6
assert arr1.min() > 0 - eps
assert arr1.max() < 1 + eps
assert arr2.min() > 0 - eps
assert arr2.max() < 1 + eps
if not bins:
bins = [x / 10 for x in range(11)]
hist1 = np.histogram(arr1, bins=bins)[0] / arr1.size
hist2 = np.histogram(arr2, bins=bins)[0] / arr2.size
assert abs(hist1.sum() - 1.0) < eps
assert abs(hist2.sum() - 1.0) < eps
sqerr = (hist1 - hist2) ** 2
return sqerr.sum()
def calc_downsample(w, h, target=400):
"""Calculate downsampling value."""
if w > h:
return h / target
elif h >= w:
return w / target
@click.command()
@click.argument("source")
@click.argument("reference")
@click.option("--downsample", "-d", type=int, default=None)
@click.option("--steps", "-s", type=int, default=5000)
@click.option("--plot/--no-plot", default=True)
if __name__ == "__main__":
main()
|
mapbox/rio-color | scripts/optimize_color.py | ColorEstimator.move | python | def move(self):
k = random.choice(self.keys)
multiplier = random.choice((0.95, 1.05))
invalid_key = True
while invalid_key:
# make sure bias doesn't exceed 1.0
if k == "bias":
if self.state[k] > 0.909:
k = random.choice(self.keys)
continue
invalid_key = False
newval = self.state[k] * multiplier
self.state[k] = newval | Create a state change. | train | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/scripts/optimize_color.py#L77-L93 | null | class ColorEstimator(Annealer):
"""Optimizes color using simulated annealing"""
keys = "gamma_red,gamma_green,gamma_blue,contrast".split(",")
def __init__(self, source, reference, state=None):
"""Create a new instance"""
self.src = source.copy()
self.ref = reference.copy()
if not state:
params = dict(gamma_red=1.0, gamma_green=1.0, gamma_blue=1.0, contrast=10)
else:
if self._validate(state):
params = state
else:
raise ValueError("invalid state")
super(ColorEstimator, self).__init__(params)
def validate(self):
"""Validate keys."""
# todo validate values bt 0..1
for k in self.keys:
if k not in self.state:
return False
def cmd(self, state):
"""Get color formula representation of the state."""
ops = (
"gamma r {gamma_red:.2f}, gamma g {gamma_green:.2f}, gamma b {gamma_blue:.2f}, "
"sigmoidal rgb {contrast:.2f} 0.5".format(**state)
)
return ops
def apply_color(self, arr, state):
"""Apply color formula to an array."""
ops = self.cmd(state)
for func in parse_operations(ops):
arr = func(arr)
return arr
def energy(self):
"""Calculate state's energy."""
arr = self.src.copy()
arr = self.apply_color(arr, self.state)
scores = [histogram_distance(self.ref[i], arr[i]) for i in range(3)]
# Important: scale by 100 for readability
return sum(scores) * 100
def to_dict(self):
"""Serialize as a dict."""
return dict(best=self.best_state, current=self.state)
def update(self, step, T, E, acceptance, improvement):
"""Print progress."""
if acceptance is None:
acceptance = 0
if improvement is None:
improvement = 0
if step > 0:
elapsed = time.time() - self.start
remain = (self.steps - step) * (elapsed / step)
# print('Time {} ({} Remaing)'.format(time_string(elapsed), time_string(remain)))
else:
elapsed = 0
remain = 0
curr = self.cmd(self.state)
curr_score = float(E)
best = self.cmd(self.best_state)
best_score = self.best_energy
report = progress_report(
curr,
best,
curr_score,
best_score,
step,
self.steps,
acceptance * 100,
improvement * 100,
time_string(elapsed),
time_string(remain),
)
print(report)
if fig:
imgs[1].set_data(
reshape_as_image(self.apply_color(self.src.copy(), self.state))
)
imgs[2].set_data(
reshape_as_image(self.apply_color(self.src.copy(), self.best_state))
)
if txt:
txt.set_text(report)
fig.canvas.draw()
|
mapbox/rio-color | scripts/optimize_color.py | ColorEstimator.apply_color | python | def apply_color(self, arr, state):
ops = self.cmd(state)
for func in parse_operations(ops):
arr = func(arr)
return arr | Apply color formula to an array. | train | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/scripts/optimize_color.py#L103-L108 | [
"def parse_operations(ops_string):\n \"\"\"Takes a string of operations written with a handy DSL\n\n \"OPERATION-NAME BANDS ARG1 ARG2 OPERATION-NAME BANDS ARG\"\n\n And returns a list of functions, each of which take and return ndarrays\n \"\"\"\n band_lookup = {\"r\": 1, \"g\": 2, \"b\": 3}\n cou... | class ColorEstimator(Annealer):
"""Optimizes color using simulated annealing"""
keys = "gamma_red,gamma_green,gamma_blue,contrast".split(",")
def __init__(self, source, reference, state=None):
"""Create a new instance"""
self.src = source.copy()
self.ref = reference.copy()
if not state:
params = dict(gamma_red=1.0, gamma_green=1.0, gamma_blue=1.0, contrast=10)
else:
if self._validate(state):
params = state
else:
raise ValueError("invalid state")
super(ColorEstimator, self).__init__(params)
def validate(self):
"""Validate keys."""
# todo validate values bt 0..1
for k in self.keys:
if k not in self.state:
return False
def move(self):
"""Create a state change."""
k = random.choice(self.keys)
multiplier = random.choice((0.95, 1.05))
invalid_key = True
while invalid_key:
# make sure bias doesn't exceed 1.0
if k == "bias":
if self.state[k] > 0.909:
k = random.choice(self.keys)
continue
invalid_key = False
newval = self.state[k] * multiplier
self.state[k] = newval
def cmd(self, state):
"""Get color formula representation of the state."""
ops = (
"gamma r {gamma_red:.2f}, gamma g {gamma_green:.2f}, gamma b {gamma_blue:.2f}, "
"sigmoidal rgb {contrast:.2f} 0.5".format(**state)
)
return ops
def energy(self):
"""Calculate state's energy."""
arr = self.src.copy()
arr = self.apply_color(arr, self.state)
scores = [histogram_distance(self.ref[i], arr[i]) for i in range(3)]
# Important: scale by 100 for readability
return sum(scores) * 100
def to_dict(self):
"""Serialize as a dict."""
return dict(best=self.best_state, current=self.state)
def update(self, step, T, E, acceptance, improvement):
"""Print progress."""
if acceptance is None:
acceptance = 0
if improvement is None:
improvement = 0
if step > 0:
elapsed = time.time() - self.start
remain = (self.steps - step) * (elapsed / step)
# print('Time {} ({} Remaing)'.format(time_string(elapsed), time_string(remain)))
else:
elapsed = 0
remain = 0
curr = self.cmd(self.state)
curr_score = float(E)
best = self.cmd(self.best_state)
best_score = self.best_energy
report = progress_report(
curr,
best,
curr_score,
best_score,
step,
self.steps,
acceptance * 100,
improvement * 100,
time_string(elapsed),
time_string(remain),
)
print(report)
if fig:
imgs[1].set_data(
reshape_as_image(self.apply_color(self.src.copy(), self.state))
)
imgs[2].set_data(
reshape_as_image(self.apply_color(self.src.copy(), self.best_state))
)
if txt:
txt.set_text(report)
fig.canvas.draw()
|
mapbox/rio-color | scripts/optimize_color.py | ColorEstimator.energy | python | def energy(self):
arr = self.src.copy()
arr = self.apply_color(arr, self.state)
scores = [histogram_distance(self.ref[i], arr[i]) for i in range(3)]
# Important: scale by 100 for readability
return sum(scores) * 100 | Calculate state's energy. | train | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/scripts/optimize_color.py#L110-L118 | null | class ColorEstimator(Annealer):
"""Optimizes color using simulated annealing"""
keys = "gamma_red,gamma_green,gamma_blue,contrast".split(",")
def __init__(self, source, reference, state=None):
"""Create a new instance"""
self.src = source.copy()
self.ref = reference.copy()
if not state:
params = dict(gamma_red=1.0, gamma_green=1.0, gamma_blue=1.0, contrast=10)
else:
if self._validate(state):
params = state
else:
raise ValueError("invalid state")
super(ColorEstimator, self).__init__(params)
def validate(self):
"""Validate keys."""
# todo validate values bt 0..1
for k in self.keys:
if k not in self.state:
return False
def move(self):
"""Create a state change."""
k = random.choice(self.keys)
multiplier = random.choice((0.95, 1.05))
invalid_key = True
while invalid_key:
# make sure bias doesn't exceed 1.0
if k == "bias":
if self.state[k] > 0.909:
k = random.choice(self.keys)
continue
invalid_key = False
newval = self.state[k] * multiplier
self.state[k] = newval
def cmd(self, state):
"""Get color formula representation of the state."""
ops = (
"gamma r {gamma_red:.2f}, gamma g {gamma_green:.2f}, gamma b {gamma_blue:.2f}, "
"sigmoidal rgb {contrast:.2f} 0.5".format(**state)
)
return ops
def apply_color(self, arr, state):
"""Apply color formula to an array."""
ops = self.cmd(state)
for func in parse_operations(ops):
arr = func(arr)
return arr
def to_dict(self):
"""Serialize as a dict."""
return dict(best=self.best_state, current=self.state)
def update(self, step, T, E, acceptance, improvement):
"""Print progress."""
if acceptance is None:
acceptance = 0
if improvement is None:
improvement = 0
if step > 0:
elapsed = time.time() - self.start
remain = (self.steps - step) * (elapsed / step)
# print('Time {} ({} Remaing)'.format(time_string(elapsed), time_string(remain)))
else:
elapsed = 0
remain = 0
curr = self.cmd(self.state)
curr_score = float(E)
best = self.cmd(self.best_state)
best_score = self.best_energy
report = progress_report(
curr,
best,
curr_score,
best_score,
step,
self.steps,
acceptance * 100,
improvement * 100,
time_string(elapsed),
time_string(remain),
)
print(report)
if fig:
imgs[1].set_data(
reshape_as_image(self.apply_color(self.src.copy(), self.state))
)
imgs[2].set_data(
reshape_as_image(self.apply_color(self.src.copy(), self.best_state))
)
if txt:
txt.set_text(report)
fig.canvas.draw()
|
mapbox/rio-color | scripts/optimize_color.py | ColorEstimator.update | python | def update(self, step, T, E, acceptance, improvement):
if acceptance is None:
acceptance = 0
if improvement is None:
improvement = 0
if step > 0:
elapsed = time.time() - self.start
remain = (self.steps - step) * (elapsed / step)
# print('Time {} ({} Remaing)'.format(time_string(elapsed), time_string(remain)))
else:
elapsed = 0
remain = 0
curr = self.cmd(self.state)
curr_score = float(E)
best = self.cmd(self.best_state)
best_score = self.best_energy
report = progress_report(
curr,
best,
curr_score,
best_score,
step,
self.steps,
acceptance * 100,
improvement * 100,
time_string(elapsed),
time_string(remain),
)
print(report)
if fig:
imgs[1].set_data(
reshape_as_image(self.apply_color(self.src.copy(), self.state))
)
imgs[2].set_data(
reshape_as_image(self.apply_color(self.src.copy(), self.best_state))
)
if txt:
txt.set_text(report)
fig.canvas.draw() | Print progress. | train | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/scripts/optimize_color.py#L124-L165 | [
"def time_string(seconds):\n \"\"\"Returns time in seconds as a string formatted HHHH:MM:SS.\"\"\"\n s = int(round(seconds)) # round to nearest second\n h, s = divmod(s, 3600) # get hours and remainder\n m, s = divmod(s, 60) # split remainder into minutes and seconds\n return \"%2i:%02i:%02i\" % (... | class ColorEstimator(Annealer):
"""Optimizes color using simulated annealing"""
keys = "gamma_red,gamma_green,gamma_blue,contrast".split(",")
def __init__(self, source, reference, state=None):
"""Create a new instance"""
self.src = source.copy()
self.ref = reference.copy()
if not state:
params = dict(gamma_red=1.0, gamma_green=1.0, gamma_blue=1.0, contrast=10)
else:
if self._validate(state):
params = state
else:
raise ValueError("invalid state")
super(ColorEstimator, self).__init__(params)
def validate(self):
"""Validate keys."""
# todo validate values bt 0..1
for k in self.keys:
if k not in self.state:
return False
def move(self):
"""Create a state change."""
k = random.choice(self.keys)
multiplier = random.choice((0.95, 1.05))
invalid_key = True
while invalid_key:
# make sure bias doesn't exceed 1.0
if k == "bias":
if self.state[k] > 0.909:
k = random.choice(self.keys)
continue
invalid_key = False
newval = self.state[k] * multiplier
self.state[k] = newval
def cmd(self, state):
"""Get color formula representation of the state."""
ops = (
"gamma r {gamma_red:.2f}, gamma g {gamma_green:.2f}, gamma b {gamma_blue:.2f}, "
"sigmoidal rgb {contrast:.2f} 0.5".format(**state)
)
return ops
def apply_color(self, arr, state):
"""Apply color formula to an array."""
ops = self.cmd(state)
for func in parse_operations(ops):
arr = func(arr)
return arr
def energy(self):
"""Calculate state's energy."""
arr = self.src.copy()
arr = self.apply_color(arr, self.state)
scores = [histogram_distance(self.ref[i], arr[i]) for i in range(3)]
# Important: scale by 100 for readability
return sum(scores) * 100
def to_dict(self):
"""Serialize as a dict."""
return dict(best=self.best_state, current=self.state)
|
mapbox/rio-color | rio_color/workers.py | atmos_worker | python | def atmos_worker(srcs, window, ij, args):
src = srcs[0]
rgb = src.read(window=window)
rgb = to_math_type(rgb)
atmos = simple_atmo(rgb, args["atmo"], args["contrast"], args["bias"])
# should be scaled 0 to 1, scale to outtype
return scale_dtype(atmos, args["out_dtype"]) | A simple atmospheric correction user function. | train | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/rio_color/workers.py#L9-L18 | [
"def simple_atmo(rgb, haze, contrast, bias):\n \"\"\"\n A simple, static (non-adaptive) atmospheric correction function.\n\n Parameters\n ----------\n haze: float\n Amount of haze to adjust for. For example, 0.03\n contrast : integer\n Enhances the intensity differences between the l... | """Color functions for use with rio-mucho."""
from .operations import parse_operations, simple_atmo
from .utils import to_math_type, scale_dtype
# Rio workers
def color_worker(srcs, window, ij, args):
"""A user function."""
src = srcs[0]
arr = src.read(window=window)
arr = to_math_type(arr)
for func in parse_operations(args["ops_string"]):
arr = func(arr)
# scaled 0 to 1, now scale to outtype
return scale_dtype(arr, args["out_dtype"])
|
mapbox/rio-color | rio_color/workers.py | color_worker | python | def color_worker(srcs, window, ij, args):
src = srcs[0]
arr = src.read(window=window)
arr = to_math_type(arr)
for func in parse_operations(args["ops_string"]):
arr = func(arr)
# scaled 0 to 1, now scale to outtype
return scale_dtype(arr, args["out_dtype"]) | A user function. | train | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/rio_color/workers.py#L21-L31 | [
"def parse_operations(ops_string):\n \"\"\"Takes a string of operations written with a handy DSL\n\n \"OPERATION-NAME BANDS ARG1 ARG2 OPERATION-NAME BANDS ARG\"\n\n And returns a list of functions, each of which take and return ndarrays\n \"\"\"\n band_lookup = {\"r\": 1, \"g\": 2, \"b\": 3}\n cou... | """Color functions for use with rio-mucho."""
from .operations import parse_operations, simple_atmo
from .utils import to_math_type, scale_dtype
# Rio workers
def atmos_worker(srcs, window, ij, args):
"""A simple atmospheric correction user function."""
src = srcs[0]
rgb = src.read(window=window)
rgb = to_math_type(rgb)
atmos = simple_atmo(rgb, args["atmo"], args["contrast"], args["bias"])
# should be scaled 0 to 1, scale to outtype
return scale_dtype(atmos, args["out_dtype"])
|
mpdavis/python-jose | jose/backends/pycrypto_backend.py | _der_to_pem | python | def _der_to_pem(der_key, marker):
pem_key_chunks = [('-----BEGIN %s-----' % marker).encode('utf-8')]
# Limit base64 output lines to 64 characters by limiting input lines to 48 characters.
for chunk_start in range(0, len(der_key), 48):
pem_key_chunks.append(b64encode(der_key[chunk_start:chunk_start + 48]))
pem_key_chunks.append(('-----END %s-----' % marker).encode('utf-8'))
return b'\n'.join(pem_key_chunks) | Perform a simple DER to PEM conversion. | train | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/backends/pycrypto_backend.py#L30-L42 | null | from base64 import b64encode
import six
import Crypto.Hash.SHA256
import Crypto.Hash.SHA384
import Crypto.Hash.SHA512
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Util.asn1 import DerSequence
from jose.backends.base import Key
from jose.backends._asn1 import rsa_public_key_pkcs8_to_pkcs1
from jose.utils import base64_to_long, long_to_base64
from jose.constants import ALGORITHMS
from jose.exceptions import JWKError
from jose.utils import base64url_decode
# We default to using PyCryptodome, however, if PyCrypto is installed, it is
# used instead. This is so that environments that require the use of PyCrypto
# are still supported.
if hasattr(RSA, 'RsaKey'):
_RSAKey = RSA.RsaKey
else:
_RSAKey = RSA._RSAobj
class RSAKey(Key):
"""
Performs signing and verification operations using
RSASSA-PKCS-v1_5 and the specified hash function.
This class requires PyCrypto package to be installed.
This is based off of the implementation in PyJWT 0.3.2
"""
SHA256 = Crypto.Hash.SHA256
SHA384 = Crypto.Hash.SHA384
SHA512 = Crypto.Hash.SHA512
def __init__(self, key, algorithm):
if algorithm not in ALGORITHMS.RSA:
raise JWKError('hash_alg: %s is not a valid hash algorithm' % algorithm)
self.hash_alg = {
ALGORITHMS.RS256: self.SHA256,
ALGORITHMS.RS384: self.SHA384,
ALGORITHMS.RS512: self.SHA512
}.get(algorithm)
self._algorithm = algorithm
if isinstance(key, _RSAKey):
self.prepared_key = key
return
if isinstance(key, dict):
self._process_jwk(key)
return
if isinstance(key, six.string_types):
key = key.encode('utf-8')
if isinstance(key, six.binary_type):
if key.startswith(b'-----BEGIN CERTIFICATE-----'):
try:
self._process_cert(key)
except Exception as e:
raise JWKError(e)
return
try:
self.prepared_key = RSA.importKey(key)
except Exception as e:
raise JWKError(e)
return
raise JWKError('Unable to parse an RSA_JWK from key: %s' % key)
def _process_jwk(self, jwk_dict):
if not jwk_dict.get('kty') == 'RSA':
raise JWKError("Incorrect key type. Expected: 'RSA', Recieved: %s" % jwk_dict.get('kty'))
e = base64_to_long(jwk_dict.get('e', 256))
n = base64_to_long(jwk_dict.get('n'))
params = (n, e)
if 'd' in jwk_dict:
params += (base64_to_long(jwk_dict.get('d')),)
extra_params = ['p', 'q', 'dp', 'dq', 'qi']
if any(k in jwk_dict for k in extra_params):
# Precomputed private key parameters are available.
if not all(k in jwk_dict for k in extra_params):
# These values must be present when 'p' is according to
# Section 6.3.2 of RFC7518, so if they are not we raise
# an error.
raise JWKError('Precomputed private key parameters are incomplete.')
p = base64_to_long(jwk_dict.get('p'))
q = base64_to_long(jwk_dict.get('q'))
qi = base64_to_long(jwk_dict.get('qi'))
# PyCrypto does not take the dp and dq as arguments, so we do
# not pass them. Furthermore, the parameter qi specified in
# the JWK is the inverse of q modulo p, whereas PyCrypto
# takes the inverse of p modulo q. We therefore switch the
# parameters to make the third parameter the inverse of the
# second parameter modulo the first parameter.
params += (q, p, qi)
self.prepared_key = RSA.construct(params)
return self.prepared_key
def _process_cert(self, key):
pemLines = key.replace(b' ', b'').split()
certDer = base64url_decode(b''.join(pemLines[1:-1]))
certSeq = DerSequence()
certSeq.decode(certDer)
tbsSeq = DerSequence()
tbsSeq.decode(certSeq[0])
self.prepared_key = RSA.importKey(tbsSeq[6])
return
def sign(self, msg):
try:
return PKCS1_v1_5.new(self.prepared_key).sign(self.hash_alg.new(msg))
except Exception as e:
raise JWKError(e)
def verify(self, msg, sig):
try:
return PKCS1_v1_5.new(self.prepared_key).verify(self.hash_alg.new(msg), sig)
except Exception:
return False
def is_public(self):
return not self.prepared_key.has_private()
def public_key(self):
if self.is_public():
return self
return self.__class__(self.prepared_key.publickey(), self._algorithm)
def to_pem(self, pem_format='PKCS8'):
if pem_format == 'PKCS8':
pkcs = 8
elif pem_format == 'PKCS1':
pkcs = 1
else:
raise ValueError("Invalid pem format specified: %r" % (pem_format,))
if self.is_public():
# PyCrypto/dome always export public keys as PKCS8
if pkcs == 8:
pem = self.prepared_key.exportKey('PEM')
else:
pkcs8_der = self.prepared_key.exportKey('DER')
pkcs1_der = rsa_public_key_pkcs8_to_pkcs1(pkcs8_der)
pem = _der_to_pem(pkcs1_der, 'RSA PUBLIC KEY')
return pem
else:
pem = self.prepared_key.exportKey('PEM', pkcs=pkcs)
return pem
def to_dict(self):
data = {
'alg': self._algorithm,
'kty': 'RSA',
'n': long_to_base64(self.prepared_key.n),
'e': long_to_base64(self.prepared_key.e),
}
if not self.is_public():
# Section 6.3.2 of RFC7518 prescribes that when we include the
# optional parameters p and q, we must also include the values of
# dp and dq, which are not readily available from PyCrypto - so we
# calculate them. Moreover, PyCrypto stores the inverse of p
# modulo q rather than the inverse of q modulo p, so we switch
# p and q. As far as I can tell, this is OK - RFC7518 only
# asserts that p is the 'first factor', but does not specify
# what 'first' means in this case.
dp = self.prepared_key.d % (self.prepared_key.p - 1)
dq = self.prepared_key.d % (self.prepared_key.q - 1)
data.update({
'd': long_to_base64(self.prepared_key.d),
'p': long_to_base64(self.prepared_key.q),
'q': long_to_base64(self.prepared_key.p),
'dp': long_to_base64(dq),
'dq': long_to_base64(dp),
'qi': long_to_base64(self.prepared_key.u),
})
return data
|
mpdavis/python-jose | jose/backends/_asn1.py | rsa_private_key_pkcs8_to_pkcs1 | python | def rsa_private_key_pkcs8_to_pkcs1(pkcs8_key):
decoded_values = decoder.decode(pkcs8_key, asn1Spec=PKCS8PrivateKey())
try:
decoded_key = decoded_values[0]
except IndexError:
raise ValueError("Invalid private key encoding")
return decoded_key["privateKey"] | Convert a PKCS8-encoded RSA private key to PKCS1. | train | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/backends/_asn1.py#L36-L45 | null | """ASN1 encoding helpers for converting between PKCS1 and PKCS8.
Required by rsa_backend and pycrypto_backend but not cryptography_backend.
"""
from pyasn1.codec.der import decoder, encoder
from pyasn1.type import namedtype, univ
RSA_ENCRYPTION_ASN1_OID = "1.2.840.113549.1.1.1"
class RsaAlgorithmIdentifier(univ.Sequence):
"""ASN1 structure for recording RSA PrivateKeyAlgorithm identifiers."""
componentType = namedtype.NamedTypes(
namedtype.NamedType("rsaEncryption", univ.ObjectIdentifier()),
namedtype.NamedType("parameters", univ.Null())
)
class PKCS8PrivateKey(univ.Sequence):
"""ASN1 structure for recording PKCS8 private keys."""
componentType = namedtype.NamedTypes(
namedtype.NamedType("version", univ.Integer()),
namedtype.NamedType("privateKeyAlgorithm", RsaAlgorithmIdentifier()),
namedtype.NamedType("privateKey", univ.OctetString())
)
class PublicKeyInfo(univ.Sequence):
"""ASN1 structure for recording PKCS8 public keys."""
componentType = namedtype.NamedTypes(
namedtype.NamedType("algorithm", RsaAlgorithmIdentifier()),
namedtype.NamedType("publicKey", univ.BitString())
)
def rsa_private_key_pkcs1_to_pkcs8(pkcs1_key):
"""Convert a PKCS1-encoded RSA private key to PKCS8."""
algorithm = RsaAlgorithmIdentifier()
algorithm["rsaEncryption"] = RSA_ENCRYPTION_ASN1_OID
pkcs8_key = PKCS8PrivateKey()
pkcs8_key["version"] = 0
pkcs8_key["privateKeyAlgorithm"] = algorithm
pkcs8_key["privateKey"] = pkcs1_key
return encoder.encode(pkcs8_key)
def rsa_public_key_pkcs1_to_pkcs8(pkcs1_key):
"""Convert a PKCS1-encoded RSA private key to PKCS8."""
algorithm = RsaAlgorithmIdentifier()
algorithm["rsaEncryption"] = RSA_ENCRYPTION_ASN1_OID
pkcs8_key = PublicKeyInfo()
pkcs8_key["algorithm"] = algorithm
pkcs8_key["publicKey"] = univ.BitString.fromOctetString(pkcs1_key)
return encoder.encode(pkcs8_key)
def rsa_public_key_pkcs8_to_pkcs1(pkcs8_key):
"""Convert a PKCS8-encoded RSA private key to PKCS1."""
decoded_values = decoder.decode(pkcs8_key, asn1Spec=PublicKeyInfo())
try:
decoded_key = decoded_values[0]
except IndexError:
raise ValueError("Invalid public key encoding.")
return decoded_key["publicKey"].asOctets()
|
mpdavis/python-jose | jose/backends/_asn1.py | rsa_private_key_pkcs1_to_pkcs8 | python | def rsa_private_key_pkcs1_to_pkcs8(pkcs1_key):
algorithm = RsaAlgorithmIdentifier()
algorithm["rsaEncryption"] = RSA_ENCRYPTION_ASN1_OID
pkcs8_key = PKCS8PrivateKey()
pkcs8_key["version"] = 0
pkcs8_key["privateKeyAlgorithm"] = algorithm
pkcs8_key["privateKey"] = pkcs1_key
return encoder.encode(pkcs8_key) | Convert a PKCS1-encoded RSA private key to PKCS8. | train | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/backends/_asn1.py#L48-L58 | null | """ASN1 encoding helpers for converting between PKCS1 and PKCS8.
Required by rsa_backend and pycrypto_backend but not cryptography_backend.
"""
from pyasn1.codec.der import decoder, encoder
from pyasn1.type import namedtype, univ
RSA_ENCRYPTION_ASN1_OID = "1.2.840.113549.1.1.1"
class RsaAlgorithmIdentifier(univ.Sequence):
"""ASN1 structure for recording RSA PrivateKeyAlgorithm identifiers."""
componentType = namedtype.NamedTypes(
namedtype.NamedType("rsaEncryption", univ.ObjectIdentifier()),
namedtype.NamedType("parameters", univ.Null())
)
class PKCS8PrivateKey(univ.Sequence):
"""ASN1 structure for recording PKCS8 private keys."""
componentType = namedtype.NamedTypes(
namedtype.NamedType("version", univ.Integer()),
namedtype.NamedType("privateKeyAlgorithm", RsaAlgorithmIdentifier()),
namedtype.NamedType("privateKey", univ.OctetString())
)
class PublicKeyInfo(univ.Sequence):
"""ASN1 structure for recording PKCS8 public keys."""
componentType = namedtype.NamedTypes(
namedtype.NamedType("algorithm", RsaAlgorithmIdentifier()),
namedtype.NamedType("publicKey", univ.BitString())
)
def rsa_private_key_pkcs8_to_pkcs1(pkcs8_key):
"""Convert a PKCS8-encoded RSA private key to PKCS1."""
decoded_values = decoder.decode(pkcs8_key, asn1Spec=PKCS8PrivateKey())
try:
decoded_key = decoded_values[0]
except IndexError:
raise ValueError("Invalid private key encoding")
return decoded_key["privateKey"]
def rsa_public_key_pkcs1_to_pkcs8(pkcs1_key):
"""Convert a PKCS1-encoded RSA private key to PKCS8."""
algorithm = RsaAlgorithmIdentifier()
algorithm["rsaEncryption"] = RSA_ENCRYPTION_ASN1_OID
pkcs8_key = PublicKeyInfo()
pkcs8_key["algorithm"] = algorithm
pkcs8_key["publicKey"] = univ.BitString.fromOctetString(pkcs1_key)
return encoder.encode(pkcs8_key)
def rsa_public_key_pkcs8_to_pkcs1(pkcs8_key):
"""Convert a PKCS8-encoded RSA private key to PKCS1."""
decoded_values = decoder.decode(pkcs8_key, asn1Spec=PublicKeyInfo())
try:
decoded_key = decoded_values[0]
except IndexError:
raise ValueError("Invalid public key encoding.")
return decoded_key["publicKey"].asOctets()
|
mpdavis/python-jose | jose/backends/_asn1.py | rsa_public_key_pkcs1_to_pkcs8 | python | def rsa_public_key_pkcs1_to_pkcs8(pkcs1_key):
algorithm = RsaAlgorithmIdentifier()
algorithm["rsaEncryption"] = RSA_ENCRYPTION_ASN1_OID
pkcs8_key = PublicKeyInfo()
pkcs8_key["algorithm"] = algorithm
pkcs8_key["publicKey"] = univ.BitString.fromOctetString(pkcs1_key)
return encoder.encode(pkcs8_key) | Convert a PKCS1-encoded RSA private key to PKCS8. | train | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/backends/_asn1.py#L61-L70 | null | """ASN1 encoding helpers for converting between PKCS1 and PKCS8.
Required by rsa_backend and pycrypto_backend but not cryptography_backend.
"""
from pyasn1.codec.der import decoder, encoder
from pyasn1.type import namedtype, univ
RSA_ENCRYPTION_ASN1_OID = "1.2.840.113549.1.1.1"
class RsaAlgorithmIdentifier(univ.Sequence):
"""ASN1 structure for recording RSA PrivateKeyAlgorithm identifiers."""
componentType = namedtype.NamedTypes(
namedtype.NamedType("rsaEncryption", univ.ObjectIdentifier()),
namedtype.NamedType("parameters", univ.Null())
)
class PKCS8PrivateKey(univ.Sequence):
"""ASN1 structure for recording PKCS8 private keys."""
componentType = namedtype.NamedTypes(
namedtype.NamedType("version", univ.Integer()),
namedtype.NamedType("privateKeyAlgorithm", RsaAlgorithmIdentifier()),
namedtype.NamedType("privateKey", univ.OctetString())
)
class PublicKeyInfo(univ.Sequence):
"""ASN1 structure for recording PKCS8 public keys."""
componentType = namedtype.NamedTypes(
namedtype.NamedType("algorithm", RsaAlgorithmIdentifier()),
namedtype.NamedType("publicKey", univ.BitString())
)
def rsa_private_key_pkcs8_to_pkcs1(pkcs8_key):
"""Convert a PKCS8-encoded RSA private key to PKCS1."""
decoded_values = decoder.decode(pkcs8_key, asn1Spec=PKCS8PrivateKey())
try:
decoded_key = decoded_values[0]
except IndexError:
raise ValueError("Invalid private key encoding")
return decoded_key["privateKey"]
def rsa_private_key_pkcs1_to_pkcs8(pkcs1_key):
"""Convert a PKCS1-encoded RSA private key to PKCS8."""
algorithm = RsaAlgorithmIdentifier()
algorithm["rsaEncryption"] = RSA_ENCRYPTION_ASN1_OID
pkcs8_key = PKCS8PrivateKey()
pkcs8_key["version"] = 0
pkcs8_key["privateKeyAlgorithm"] = algorithm
pkcs8_key["privateKey"] = pkcs1_key
return encoder.encode(pkcs8_key)
def rsa_public_key_pkcs8_to_pkcs1(pkcs8_key):
"""Convert a PKCS8-encoded RSA private key to PKCS1."""
decoded_values = decoder.decode(pkcs8_key, asn1Spec=PublicKeyInfo())
try:
decoded_key = decoded_values[0]
except IndexError:
raise ValueError("Invalid public key encoding.")
return decoded_key["publicKey"].asOctets()
|
mpdavis/python-jose | jose/backends/_asn1.py | rsa_public_key_pkcs8_to_pkcs1 | python | def rsa_public_key_pkcs8_to_pkcs1(pkcs8_key):
decoded_values = decoder.decode(pkcs8_key, asn1Spec=PublicKeyInfo())
try:
decoded_key = decoded_values[0]
except IndexError:
raise ValueError("Invalid public key encoding.")
return decoded_key["publicKey"].asOctets() | Convert a PKCS8-encoded RSA private key to PKCS1. | train | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/backends/_asn1.py#L73-L82 | null | """ASN1 encoding helpers for converting between PKCS1 and PKCS8.
Required by rsa_backend and pycrypto_backend but not cryptography_backend.
"""
from pyasn1.codec.der import decoder, encoder
from pyasn1.type import namedtype, univ
RSA_ENCRYPTION_ASN1_OID = "1.2.840.113549.1.1.1"
class RsaAlgorithmIdentifier(univ.Sequence):
"""ASN1 structure for recording RSA PrivateKeyAlgorithm identifiers."""
componentType = namedtype.NamedTypes(
namedtype.NamedType("rsaEncryption", univ.ObjectIdentifier()),
namedtype.NamedType("parameters", univ.Null())
)
class PKCS8PrivateKey(univ.Sequence):
"""ASN1 structure for recording PKCS8 private keys."""
componentType = namedtype.NamedTypes(
namedtype.NamedType("version", univ.Integer()),
namedtype.NamedType("privateKeyAlgorithm", RsaAlgorithmIdentifier()),
namedtype.NamedType("privateKey", univ.OctetString())
)
class PublicKeyInfo(univ.Sequence):
"""ASN1 structure for recording PKCS8 public keys."""
componentType = namedtype.NamedTypes(
namedtype.NamedType("algorithm", RsaAlgorithmIdentifier()),
namedtype.NamedType("publicKey", univ.BitString())
)
def rsa_private_key_pkcs8_to_pkcs1(pkcs8_key):
"""Convert a PKCS8-encoded RSA private key to PKCS1."""
decoded_values = decoder.decode(pkcs8_key, asn1Spec=PKCS8PrivateKey())
try:
decoded_key = decoded_values[0]
except IndexError:
raise ValueError("Invalid private key encoding")
return decoded_key["privateKey"]
def rsa_private_key_pkcs1_to_pkcs8(pkcs1_key):
"""Convert a PKCS1-encoded RSA private key to PKCS8."""
algorithm = RsaAlgorithmIdentifier()
algorithm["rsaEncryption"] = RSA_ENCRYPTION_ASN1_OID
pkcs8_key = PKCS8PrivateKey()
pkcs8_key["version"] = 0
pkcs8_key["privateKeyAlgorithm"] = algorithm
pkcs8_key["privateKey"] = pkcs1_key
return encoder.encode(pkcs8_key)
def rsa_public_key_pkcs1_to_pkcs8(pkcs1_key):
"""Convert a PKCS1-encoded RSA private key to PKCS8."""
algorithm = RsaAlgorithmIdentifier()
algorithm["rsaEncryption"] = RSA_ENCRYPTION_ASN1_OID
pkcs8_key = PublicKeyInfo()
pkcs8_key["algorithm"] = algorithm
pkcs8_key["publicKey"] = univ.BitString.fromOctetString(pkcs1_key)
return encoder.encode(pkcs8_key)
|
mpdavis/python-jose | jose/backends/cryptography_backend.py | CryptographyECKey._der_to_raw | python | def _der_to_raw(self, der_signature):
r, s = decode_dss_signature(der_signature)
component_length = self._sig_component_length()
return int_to_bytes(r, component_length) + int_to_bytes(s, component_length) | Convert signature from DER encoding to RAW encoding. | train | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/backends/cryptography_backend.py#L109-L113 | [
"def _sig_component_length(self):\n \"\"\"Determine the correct serialization length for an encoded signature component.\n\n This is the number of bytes required to encode the maximum key value.\n \"\"\"\n return int(math.ceil(self.prepared_key.key_size / 8.0))\n"
] | class CryptographyECKey(Key):
SHA256 = hashes.SHA256
SHA384 = hashes.SHA384
SHA512 = hashes.SHA512
def __init__(self, key, algorithm, cryptography_backend=default_backend):
if algorithm not in ALGORITHMS.EC:
raise JWKError('hash_alg: %s is not a valid hash algorithm' % algorithm)
self.hash_alg = {
ALGORITHMS.ES256: self.SHA256,
ALGORITHMS.ES384: self.SHA384,
ALGORITHMS.ES512: self.SHA512
}.get(algorithm)
self._algorithm = algorithm
self.cryptography_backend = cryptography_backend
if hasattr(key, 'public_bytes') or hasattr(key, 'private_bytes'):
self.prepared_key = key
return
if None not in (EcdsaSigningKey, EcdsaVerifyingKey) and isinstance(key, (EcdsaSigningKey, EcdsaVerifyingKey)):
# convert to PEM and let cryptography below load it as PEM
key = key.to_pem().decode('utf-8')
if isinstance(key, dict):
self.prepared_key = self._process_jwk(key)
return
if isinstance(key, six.string_types):
key = key.encode('utf-8')
if isinstance(key, six.binary_type):
# Attempt to load key. We don't know if it's
# a Public Key or a Private Key, so we try
# the Public Key first.
try:
try:
key = load_pem_public_key(key, self.cryptography_backend())
except ValueError:
key = load_pem_private_key(key, password=None, backend=self.cryptography_backend())
except Exception as e:
raise JWKError(e)
self.prepared_key = key
return
raise JWKError('Unable to parse an ECKey from key: %s' % key)
def _process_jwk(self, jwk_dict):
if not jwk_dict.get('kty') == 'EC':
raise JWKError("Incorrect key type. Expected: 'EC', Received: %s" % jwk_dict.get('kty'))
if not all(k in jwk_dict for k in ['x', 'y', 'crv']):
raise JWKError('Mandatory parameters are missing')
x = base64_to_long(jwk_dict.get('x'))
y = base64_to_long(jwk_dict.get('y'))
curve = {
'P-256': ec.SECP256R1,
'P-384': ec.SECP384R1,
'P-521': ec.SECP521R1,
}[jwk_dict['crv']]
public = ec.EllipticCurvePublicNumbers(x, y, curve())
if 'd' in jwk_dict:
d = base64_to_long(jwk_dict.get('d'))
private = ec.EllipticCurvePrivateNumbers(d, public)
return private.private_key(self.cryptography_backend())
else:
return public.public_key(self.cryptography_backend())
def _sig_component_length(self):
"""Determine the correct serialization length for an encoded signature component.
This is the number of bytes required to encode the maximum key value.
"""
return int(math.ceil(self.prepared_key.key_size / 8.0))
def _raw_to_der(self, raw_signature):
"""Convert signature from RAW encoding to DER encoding."""
component_length = self._sig_component_length()
if len(raw_signature) != int(2 * component_length):
raise ValueError("Invalid signature")
r_bytes = raw_signature[:component_length]
s_bytes = raw_signature[component_length:]
r = int_from_bytes(r_bytes, "big")
s = int_from_bytes(s_bytes, "big")
return encode_dss_signature(r, s)
def sign(self, msg):
if self.hash_alg.digest_size * 8 > self.prepared_key.curve.key_size:
raise TypeError("this curve (%s) is too short "
"for your digest (%d)" % (self.prepared_key.curve.name,
8 * self.hash_alg.digest_size))
signature = self.prepared_key.sign(msg, ec.ECDSA(self.hash_alg()))
return self._der_to_raw(signature)
def verify(self, msg, sig):
try:
signature = self._raw_to_der(sig)
self.prepared_key.verify(signature, msg, ec.ECDSA(self.hash_alg()))
return True
except Exception:
return False
def is_public(self):
return hasattr(self.prepared_key, 'public_bytes')
def public_key(self):
if self.is_public():
return self
return self.__class__(self.prepared_key.public_key(), self._algorithm)
def to_pem(self):
if self.is_public():
pem = self.prepared_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
return pem
pem = self.prepared_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
)
return pem
def to_dict(self):
if not self.is_public():
public_key = self.prepared_key.public_key()
else:
public_key = self.prepared_key
crv = {
'secp256r1': 'P-256',
'secp384r1': 'P-384',
'secp521r1': 'P-521',
}[self.prepared_key.curve.name]
# Calculate the key size in bytes. Section 6.2.1.2 and 6.2.1.3 of
# RFC7518 prescribes that the 'x', 'y' and 'd' parameters of the curve
# points must be encoded as octed-strings of this length.
key_size = (self.prepared_key.curve.key_size + 7) // 8
data = {
'alg': self._algorithm,
'kty': 'EC',
'crv': crv,
'x': long_to_base64(public_key.public_numbers().x, size=key_size),
'y': long_to_base64(public_key.public_numbers().y, size=key_size),
}
if not self.is_public():
data['d'] = long_to_base64(
self.prepared_key.private_numbers().private_value,
size=key_size
)
return data
|
mpdavis/python-jose | jose/backends/cryptography_backend.py | CryptographyECKey._raw_to_der | python | def _raw_to_der(self, raw_signature):
component_length = self._sig_component_length()
if len(raw_signature) != int(2 * component_length):
raise ValueError("Invalid signature")
r_bytes = raw_signature[:component_length]
s_bytes = raw_signature[component_length:]
r = int_from_bytes(r_bytes, "big")
s = int_from_bytes(s_bytes, "big")
return encode_dss_signature(r, s) | Convert signature from RAW encoding to DER encoding. | train | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/backends/cryptography_backend.py#L115-L125 | [
"def _sig_component_length(self):\n \"\"\"Determine the correct serialization length for an encoded signature component.\n\n This is the number of bytes required to encode the maximum key value.\n \"\"\"\n return int(math.ceil(self.prepared_key.key_size / 8.0))\n"
] | class CryptographyECKey(Key):
SHA256 = hashes.SHA256
SHA384 = hashes.SHA384
SHA512 = hashes.SHA512
def __init__(self, key, algorithm, cryptography_backend=default_backend):
if algorithm not in ALGORITHMS.EC:
raise JWKError('hash_alg: %s is not a valid hash algorithm' % algorithm)
self.hash_alg = {
ALGORITHMS.ES256: self.SHA256,
ALGORITHMS.ES384: self.SHA384,
ALGORITHMS.ES512: self.SHA512
}.get(algorithm)
self._algorithm = algorithm
self.cryptography_backend = cryptography_backend
if hasattr(key, 'public_bytes') or hasattr(key, 'private_bytes'):
self.prepared_key = key
return
if None not in (EcdsaSigningKey, EcdsaVerifyingKey) and isinstance(key, (EcdsaSigningKey, EcdsaVerifyingKey)):
# convert to PEM and let cryptography below load it as PEM
key = key.to_pem().decode('utf-8')
if isinstance(key, dict):
self.prepared_key = self._process_jwk(key)
return
if isinstance(key, six.string_types):
key = key.encode('utf-8')
if isinstance(key, six.binary_type):
# Attempt to load key. We don't know if it's
# a Public Key or a Private Key, so we try
# the Public Key first.
try:
try:
key = load_pem_public_key(key, self.cryptography_backend())
except ValueError:
key = load_pem_private_key(key, password=None, backend=self.cryptography_backend())
except Exception as e:
raise JWKError(e)
self.prepared_key = key
return
raise JWKError('Unable to parse an ECKey from key: %s' % key)
def _process_jwk(self, jwk_dict):
if not jwk_dict.get('kty') == 'EC':
raise JWKError("Incorrect key type. Expected: 'EC', Received: %s" % jwk_dict.get('kty'))
if not all(k in jwk_dict for k in ['x', 'y', 'crv']):
raise JWKError('Mandatory parameters are missing')
x = base64_to_long(jwk_dict.get('x'))
y = base64_to_long(jwk_dict.get('y'))
curve = {
'P-256': ec.SECP256R1,
'P-384': ec.SECP384R1,
'P-521': ec.SECP521R1,
}[jwk_dict['crv']]
public = ec.EllipticCurvePublicNumbers(x, y, curve())
if 'd' in jwk_dict:
d = base64_to_long(jwk_dict.get('d'))
private = ec.EllipticCurvePrivateNumbers(d, public)
return private.private_key(self.cryptography_backend())
else:
return public.public_key(self.cryptography_backend())
def _sig_component_length(self):
"""Determine the correct serialization length for an encoded signature component.
This is the number of bytes required to encode the maximum key value.
"""
return int(math.ceil(self.prepared_key.key_size / 8.0))
def _der_to_raw(self, der_signature):
"""Convert signature from DER encoding to RAW encoding."""
r, s = decode_dss_signature(der_signature)
component_length = self._sig_component_length()
return int_to_bytes(r, component_length) + int_to_bytes(s, component_length)
def sign(self, msg):
if self.hash_alg.digest_size * 8 > self.prepared_key.curve.key_size:
raise TypeError("this curve (%s) is too short "
"for your digest (%d)" % (self.prepared_key.curve.name,
8 * self.hash_alg.digest_size))
signature = self.prepared_key.sign(msg, ec.ECDSA(self.hash_alg()))
return self._der_to_raw(signature)
def verify(self, msg, sig):
try:
signature = self._raw_to_der(sig)
self.prepared_key.verify(signature, msg, ec.ECDSA(self.hash_alg()))
return True
except Exception:
return False
def is_public(self):
return hasattr(self.prepared_key, 'public_bytes')
def public_key(self):
if self.is_public():
return self
return self.__class__(self.prepared_key.public_key(), self._algorithm)
def to_pem(self):
if self.is_public():
pem = self.prepared_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
return pem
pem = self.prepared_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
)
return pem
def to_dict(self):
if not self.is_public():
public_key = self.prepared_key.public_key()
else:
public_key = self.prepared_key
crv = {
'secp256r1': 'P-256',
'secp384r1': 'P-384',
'secp521r1': 'P-521',
}[self.prepared_key.curve.name]
# Calculate the key size in bytes. Section 6.2.1.2 and 6.2.1.3 of
# RFC7518 prescribes that the 'x', 'y' and 'd' parameters of the curve
# points must be encoded as octed-strings of this length.
key_size = (self.prepared_key.curve.key_size + 7) // 8
data = {
'alg': self._algorithm,
'kty': 'EC',
'crv': crv,
'x': long_to_base64(public_key.public_numbers().x, size=key_size),
'y': long_to_base64(public_key.public_numbers().y, size=key_size),
}
if not self.is_public():
data['d'] = long_to_base64(
self.prepared_key.private_numbers().private_value,
size=key_size
)
return data
|
mpdavis/python-jose | jose/jwt.py | encode | python | def encode(claims, key, algorithm=ALGORITHMS.HS256, headers=None, access_token=None):
for time_claim in ['exp', 'iat', 'nbf']:
# Convert datetime to a intDate value in known time-format claims
if isinstance(claims.get(time_claim), datetime):
claims[time_claim] = timegm(claims[time_claim].utctimetuple())
if access_token:
claims['at_hash'] = calculate_at_hash(access_token,
ALGORITHMS.HASHES[algorithm])
return jws.sign(claims, key, headers=headers, algorithm=algorithm) | Encodes a claims set and returns a JWT string.
JWTs are JWS signed objects with a few reserved claims.
Args:
claims (dict): A claims set to sign
key (str or dict): The key to use for signing the claim set. Can be
individual JWK or JWK set.
algorithm (str, optional): The algorithm to use for signing the
the claims. Defaults to HS256.
headers (dict, optional): A set of headers that will be added to
the default headers. Any headers that are added as additional
headers will override the default headers.
access_token (str, optional): If present, the 'at_hash' claim will
be calculated and added to the claims present in the 'claims'
parameter.
Returns:
str: The string representation of the header, claims, and signature.
Raises:
JWTError: If there is an error encoding the claims.
Examples:
>>> jwt.encode({'a': 'b'}, 'secret', algorithm='HS256')
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8' | train | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/jwt.py#L23-L64 | [
"def sign(payload, key, headers=None, algorithm=ALGORITHMS.HS256):\n \"\"\"Signs a claims set and returns a JWS string.\n\n Args:\n payload (str): A string to sign\n key (str or dict): The key to use for signing the claim set. Can be\n individual JWK or JWK set.\n headers (dict... |
import json
from calendar import timegm
try:
from collections.abc import Mapping # Python3
except ImportError:
from collections import Mapping # Python2, will be depecrated in Python 3.8
from datetime import datetime
from datetime import timedelta
from six import string_types
from jose import jws
from .exceptions import JWSError
from .exceptions import JWTClaimsError
from .exceptions import JWTError
from .exceptions import ExpiredSignatureError
from .constants import ALGORITHMS
from .utils import timedelta_total_seconds, calculate_at_hash
def decode(token, key, algorithms=None, options=None, audience=None,
issuer=None, subject=None, access_token=None):
"""Verifies a JWT string's signature and validates reserved claims.
Args:
token (str): A signed JWS to be verified.
key (str or dict): A key to attempt to verify the payload with. Can be
individual JWK or JWK set.
algorithms (str or list): Valid algorithms that should be used to verify the JWS.
audience (str): The intended audience of the token. If the "aud" claim is
included in the claim set, then the audience must be included and must equal
the provided claim.
issuer (str or iterable): Acceptable value(s) for the issuer of the token.
If the "iss" claim is included in the claim set, then the issuer must be
given and the claim in the token must be among the acceptable values.
subject (str): The subject of the token. If the "sub" claim is
included in the claim set, then the subject must be included and must equal
the provided claim.
access_token (str): An access token string. If the "at_hash" claim is included in the
claim set, then the access_token must be included, and it must match
the "at_hash" claim.
options (dict): A dictionary of options for skipping validation steps.
defaults = {
'verify_signature': True,
'verify_aud': True,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': True,
'verify_jti': True,
'verify_at_hash': True,
'require_aud': False,
'require_iat': False,
'require_exp': False,
'require_nbf': False,
'require_iss': False,
'require_sub': False,
'require_jti': False,
'require_at_hash': False,
'leeway': 0,
}
Returns:
dict: The dict representation of the claims set, assuming the signature is valid
and all requested data validation passes.
Raises:
JWTError: If the signature is invalid in any way.
ExpiredSignatureError: If the signature has expired.
JWTClaimsError: If any claim is invalid in any way.
Examples:
>>> payload = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
>>> jwt.decode(payload, 'secret', algorithms='HS256')
"""
defaults = {
'verify_signature': True,
'verify_aud': True,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': True,
'verify_jti': True,
'verify_at_hash': True,
'require_aud': False,
'require_iat': False,
'require_exp': False,
'require_nbf': False,
'require_iss': False,
'require_sub': False,
'require_jti': False,
'require_at_hash': False,
'leeway': 0,
}
if options:
defaults.update(options)
verify_signature = defaults.get('verify_signature', True)
try:
payload = jws.verify(token, key, algorithms, verify=verify_signature)
except JWSError as e:
raise JWTError(e)
# Needed for at_hash verification
algorithm = jws.get_unverified_header(token)['alg']
try:
claims = json.loads(payload.decode('utf-8'))
except ValueError as e:
raise JWTError('Invalid payload string: %s' % e)
if not isinstance(claims, Mapping):
raise JWTError('Invalid payload string: must be a json object')
_validate_claims(claims, audience=audience, issuer=issuer,
subject=subject, algorithm=algorithm,
access_token=access_token,
options=defaults)
return claims
def get_unverified_header(token):
"""Returns the decoded headers without verification of any kind.
Args:
token (str): A signed JWT to decode the headers from.
Returns:
dict: The dict representation of the token headers.
Raises:
JWTError: If there is an exception decoding the token.
"""
try:
headers = jws.get_unverified_headers(token)
except Exception:
raise JWTError('Error decoding token headers.')
return headers
def get_unverified_headers(token):
"""Returns the decoded headers without verification of any kind.
This is simply a wrapper of get_unverified_header() for backwards
compatibility.
Args:
token (str): A signed JWT to decode the headers from.
Returns:
dict: The dict representation of the token headers.
Raises:
JWTError: If there is an exception decoding the token.
"""
return get_unverified_header(token)
def get_unverified_claims(token):
"""Returns the decoded claims without verification of any kind.
Args:
token (str): A signed JWT to decode the headers from.
Returns:
dict: The dict representation of the token claims.
Raises:
JWTError: If there is an exception decoding the token.
"""
try:
claims = jws.get_unverified_claims(token)
except Exception:
raise JWTError('Error decoding token claims.')
try:
claims = json.loads(claims.decode('utf-8'))
except ValueError as e:
raise JWTError('Invalid claims string: %s' % e)
if not isinstance(claims, Mapping):
raise JWTError('Invalid claims string: must be a json object')
return claims
def _validate_iat(claims):
"""Validates that the 'iat' claim is valid.
The "iat" (issued at) claim identifies the time at which the JWT was
issued. This claim can be used to determine the age of the JWT. Its
value MUST be a number containing a NumericDate value. Use of this
claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
"""
if 'iat' not in claims:
return
try:
int(claims['iat'])
except ValueError:
raise JWTClaimsError('Issued At claim (iat) must be an integer.')
def _validate_nbf(claims, leeway=0):
"""Validates that the 'nbf' claim is valid.
The "nbf" (not before) claim identifies the time before which the JWT
MUST NOT be accepted for processing. The processing of the "nbf"
claim requires that the current date/time MUST be after or equal to
the not-before date/time listed in the "nbf" claim. Implementers MAY
provide for some small leeway, usually no more than a few minutes, to
account for clock skew. Its value MUST be a number containing a
NumericDate value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
leeway (int): The number of seconds of skew that is allowed.
"""
if 'nbf' not in claims:
return
try:
nbf = int(claims['nbf'])
except ValueError:
raise JWTClaimsError('Not Before claim (nbf) must be an integer.')
now = timegm(datetime.utcnow().utctimetuple())
if nbf > (now + leeway):
raise JWTClaimsError('The token is not yet valid (nbf)')
def _validate_exp(claims, leeway=0):
"""Validates that the 'exp' claim is valid.
The "exp" (expiration time) claim identifies the expiration time on
or after which the JWT MUST NOT be accepted for processing. The
processing of the "exp" claim requires that the current date/time
MUST be before the expiration date/time listed in the "exp" claim.
Implementers MAY provide for some small leeway, usually no more than
a few minutes, to account for clock skew. Its value MUST be a number
containing a NumericDate value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
leeway (int): The number of seconds of skew that is allowed.
"""
if 'exp' not in claims:
return
try:
exp = int(claims['exp'])
except ValueError:
raise JWTClaimsError('Expiration Time claim (exp) must be an integer.')
now = timegm(datetime.utcnow().utctimetuple())
if exp < (now - leeway):
raise ExpiredSignatureError('Signature has expired.')
def _validate_aud(claims, audience=None):
"""Validates that the 'aud' claim is valid.
The "aud" (audience) claim identifies the recipients that the JWT is
intended for. Each principal intended to process the JWT MUST
identify itself with a value in the audience claim. If the principal
processing the claim does not identify itself with a value in the
"aud" claim when this claim is present, then the JWT MUST be
rejected. In the general case, the "aud" value is an array of case-
sensitive strings, each containing a StringOrURI value. In the
special case when the JWT has one audience, the "aud" value MAY be a
single case-sensitive string containing a StringOrURI value. The
interpretation of audience values is generally application specific.
Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
audience (str): The audience that is verifying the token.
"""
if 'aud' not in claims:
# if audience:
# raise JWTError('Audience claim expected, but not in claims')
return
audience_claims = claims['aud']
if isinstance(audience_claims, string_types):
audience_claims = [audience_claims]
if not isinstance(audience_claims, list):
raise JWTClaimsError('Invalid claim format in token')
if any(not isinstance(c, string_types) for c in audience_claims):
raise JWTClaimsError('Invalid claim format in token')
if audience not in audience_claims:
raise JWTClaimsError('Invalid audience')
def _validate_iss(claims, issuer=None):
"""Validates that the 'iss' claim is valid.
The "iss" (issuer) claim identifies the principal that issued the
JWT. The processing of this claim is generally application specific.
The "iss" value is a case-sensitive string containing a StringOrURI
value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
issuer (str or iterable): Acceptable value(s) for the issuer that
signed the token.
"""
if issuer is not None:
if isinstance(issuer, string_types):
issuer = (issuer,)
if claims.get('iss') not in issuer:
raise JWTClaimsError('Invalid issuer')
def _validate_sub(claims, subject=None):
"""Validates that the 'sub' claim is valid.
The "sub" (subject) claim identifies the principal that is the
subject of the JWT. The claims in a JWT are normally statements
about the subject. The subject value MUST either be scoped to be
locally unique in the context of the issuer or be globally unique.
The processing of this claim is generally application specific. The
"sub" value is a case-sensitive string containing a StringOrURI
value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
subject (str): The subject of the token.
"""
if 'sub' not in claims:
return
if not isinstance(claims['sub'], string_types):
raise JWTClaimsError('Subject must be a string.')
if subject is not None:
if claims.get('sub') != subject:
raise JWTClaimsError('Invalid subject')
def _validate_jti(claims):
"""Validates that the 'jti' claim is valid.
The "jti" (JWT ID) claim provides a unique identifier for the JWT.
The identifier value MUST be assigned in a manner that ensures that
there is a negligible probability that the same value will be
accidentally assigned to a different data object; if the application
uses multiple issuers, collisions MUST be prevented among values
produced by different issuers as well. The "jti" claim can be used
to prevent the JWT from being replayed. The "jti" value is a case-
sensitive string. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
"""
if 'jti' not in claims:
return
if not isinstance(claims['jti'], string_types):
raise JWTClaimsError('JWT ID must be a string.')
def _validate_at_hash(claims, access_token, algorithm):
"""
Validates that the 'at_hash' is valid.
Its value is the base64url encoding of the left-most half of the hash
of the octets of the ASCII representation of the access_token value,
where the hash algorithm used is the hash algorithm used in the alg
Header Parameter of the ID Token's JOSE Header. For instance, if the
alg is RS256, hash the access_token value with SHA-256, then take the
left-most 128 bits and base64url encode them. The at_hash value is a
case sensitive string. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
access_token (str): The access token returned by the OpenID Provider.
algorithm (str): The algorithm used to sign the JWT, as specified by
the token headers.
"""
if 'at_hash' not in claims:
return
if not access_token:
msg = 'No access_token provided to compare against at_hash claim.'
raise JWTClaimsError(msg)
try:
expected_hash = calculate_at_hash(access_token,
ALGORITHMS.HASHES[algorithm])
except (TypeError, ValueError):
msg = 'Unable to calculate at_hash to verify against token claims.'
raise JWTClaimsError(msg)
if claims['at_hash'] != expected_hash:
raise JWTClaimsError('at_hash claim does not match access_token.')
def _validate_claims(claims, audience=None, issuer=None, subject=None,
algorithm=None, access_token=None, options=None):
leeway = options.get('leeway', 0)
if isinstance(leeway, timedelta):
leeway = timedelta_total_seconds(leeway)
for require_claim in [
e[len("require_"):] for e in options.keys() if e.startswith("require_") and options[e]
]:
if require_claim not in claims:
raise JWTError('missing required key "%s" among claims' % require_claim)
else:
options['verify_' + require_claim] = True # override verify when required
if not isinstance(audience, (string_types, type(None))):
raise JWTError('audience must be a string or None')
if options.get('verify_iat'):
_validate_iat(claims)
if options.get('verify_nbf'):
_validate_nbf(claims, leeway=leeway)
if options.get('verify_exp'):
_validate_exp(claims, leeway=leeway)
if options.get('verify_aud'):
_validate_aud(claims, audience=audience)
if options.get('verify_iss'):
_validate_iss(claims, issuer=issuer)
if options.get('verify_sub'):
_validate_sub(claims, subject=subject)
if options.get('verify_jti'):
_validate_jti(claims)
if options.get('verify_at_hash'):
_validate_at_hash(claims, access_token, algorithm)
|
mpdavis/python-jose | jose/jwt.py | decode | python | def decode(token, key, algorithms=None, options=None, audience=None,
issuer=None, subject=None, access_token=None):
defaults = {
'verify_signature': True,
'verify_aud': True,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': True,
'verify_jti': True,
'verify_at_hash': True,
'require_aud': False,
'require_iat': False,
'require_exp': False,
'require_nbf': False,
'require_iss': False,
'require_sub': False,
'require_jti': False,
'require_at_hash': False,
'leeway': 0,
}
if options:
defaults.update(options)
verify_signature = defaults.get('verify_signature', True)
try:
payload = jws.verify(token, key, algorithms, verify=verify_signature)
except JWSError as e:
raise JWTError(e)
# Needed for at_hash verification
algorithm = jws.get_unverified_header(token)['alg']
try:
claims = json.loads(payload.decode('utf-8'))
except ValueError as e:
raise JWTError('Invalid payload string: %s' % e)
if not isinstance(claims, Mapping):
raise JWTError('Invalid payload string: must be a json object')
_validate_claims(claims, audience=audience, issuer=issuer,
subject=subject, algorithm=algorithm,
access_token=access_token,
options=defaults)
return claims | Verifies a JWT string's signature and validates reserved claims.
Args:
token (str): A signed JWS to be verified.
key (str or dict): A key to attempt to verify the payload with. Can be
individual JWK or JWK set.
algorithms (str or list): Valid algorithms that should be used to verify the JWS.
audience (str): The intended audience of the token. If the "aud" claim is
included in the claim set, then the audience must be included and must equal
the provided claim.
issuer (str or iterable): Acceptable value(s) for the issuer of the token.
If the "iss" claim is included in the claim set, then the issuer must be
given and the claim in the token must be among the acceptable values.
subject (str): The subject of the token. If the "sub" claim is
included in the claim set, then the subject must be included and must equal
the provided claim.
access_token (str): An access token string. If the "at_hash" claim is included in the
claim set, then the access_token must be included, and it must match
the "at_hash" claim.
options (dict): A dictionary of options for skipping validation steps.
defaults = {
'verify_signature': True,
'verify_aud': True,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': True,
'verify_jti': True,
'verify_at_hash': True,
'require_aud': False,
'require_iat': False,
'require_exp': False,
'require_nbf': False,
'require_iss': False,
'require_sub': False,
'require_jti': False,
'require_at_hash': False,
'leeway': 0,
}
Returns:
dict: The dict representation of the claims set, assuming the signature is valid
and all requested data validation passes.
Raises:
JWTError: If the signature is invalid in any way.
ExpiredSignatureError: If the signature has expired.
JWTClaimsError: If any claim is invalid in any way.
Examples:
>>> payload = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
>>> jwt.decode(payload, 'secret', algorithms='HS256') | train | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/jwt.py#L67-L174 | [
"def verify(token, key, algorithms, verify=True):\n \"\"\"Verifies a JWS string's signature.\n\n Args:\n token (str): A signed JWS to be verified.\n key (str or dict): A key to attempt to verify the payload with. Can be\n individual JWK or JWK set.\n algorithms (str or list): V... |
import json
from calendar import timegm
try:
from collections.abc import Mapping # Python3
except ImportError:
from collections import Mapping # Python2, will be depecrated in Python 3.8
from datetime import datetime
from datetime import timedelta
from six import string_types
from jose import jws
from .exceptions import JWSError
from .exceptions import JWTClaimsError
from .exceptions import JWTError
from .exceptions import ExpiredSignatureError
from .constants import ALGORITHMS
from .utils import timedelta_total_seconds, calculate_at_hash
def encode(claims, key, algorithm=ALGORITHMS.HS256, headers=None, access_token=None):
"""Encodes a claims set and returns a JWT string.
JWTs are JWS signed objects with a few reserved claims.
Args:
claims (dict): A claims set to sign
key (str or dict): The key to use for signing the claim set. Can be
individual JWK or JWK set.
algorithm (str, optional): The algorithm to use for signing the
the claims. Defaults to HS256.
headers (dict, optional): A set of headers that will be added to
the default headers. Any headers that are added as additional
headers will override the default headers.
access_token (str, optional): If present, the 'at_hash' claim will
be calculated and added to the claims present in the 'claims'
parameter.
Returns:
str: The string representation of the header, claims, and signature.
Raises:
JWTError: If there is an error encoding the claims.
Examples:
>>> jwt.encode({'a': 'b'}, 'secret', algorithm='HS256')
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
"""
for time_claim in ['exp', 'iat', 'nbf']:
# Convert datetime to a intDate value in known time-format claims
if isinstance(claims.get(time_claim), datetime):
claims[time_claim] = timegm(claims[time_claim].utctimetuple())
if access_token:
claims['at_hash'] = calculate_at_hash(access_token,
ALGORITHMS.HASHES[algorithm])
return jws.sign(claims, key, headers=headers, algorithm=algorithm)
def get_unverified_header(token):
"""Returns the decoded headers without verification of any kind.
Args:
token (str): A signed JWT to decode the headers from.
Returns:
dict: The dict representation of the token headers.
Raises:
JWTError: If there is an exception decoding the token.
"""
try:
headers = jws.get_unverified_headers(token)
except Exception:
raise JWTError('Error decoding token headers.')
return headers
def get_unverified_headers(token):
"""Returns the decoded headers without verification of any kind.
This is simply a wrapper of get_unverified_header() for backwards
compatibility.
Args:
token (str): A signed JWT to decode the headers from.
Returns:
dict: The dict representation of the token headers.
Raises:
JWTError: If there is an exception decoding the token.
"""
return get_unverified_header(token)
def get_unverified_claims(token):
"""Returns the decoded claims without verification of any kind.
Args:
token (str): A signed JWT to decode the headers from.
Returns:
dict: The dict representation of the token claims.
Raises:
JWTError: If there is an exception decoding the token.
"""
try:
claims = jws.get_unverified_claims(token)
except Exception:
raise JWTError('Error decoding token claims.')
try:
claims = json.loads(claims.decode('utf-8'))
except ValueError as e:
raise JWTError('Invalid claims string: %s' % e)
if not isinstance(claims, Mapping):
raise JWTError('Invalid claims string: must be a json object')
return claims
def _validate_iat(claims):
"""Validates that the 'iat' claim is valid.
The "iat" (issued at) claim identifies the time at which the JWT was
issued. This claim can be used to determine the age of the JWT. Its
value MUST be a number containing a NumericDate value. Use of this
claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
"""
if 'iat' not in claims:
return
try:
int(claims['iat'])
except ValueError:
raise JWTClaimsError('Issued At claim (iat) must be an integer.')
def _validate_nbf(claims, leeway=0):
"""Validates that the 'nbf' claim is valid.
The "nbf" (not before) claim identifies the time before which the JWT
MUST NOT be accepted for processing. The processing of the "nbf"
claim requires that the current date/time MUST be after or equal to
the not-before date/time listed in the "nbf" claim. Implementers MAY
provide for some small leeway, usually no more than a few minutes, to
account for clock skew. Its value MUST be a number containing a
NumericDate value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
leeway (int): The number of seconds of skew that is allowed.
"""
if 'nbf' not in claims:
return
try:
nbf = int(claims['nbf'])
except ValueError:
raise JWTClaimsError('Not Before claim (nbf) must be an integer.')
now = timegm(datetime.utcnow().utctimetuple())
if nbf > (now + leeway):
raise JWTClaimsError('The token is not yet valid (nbf)')
def _validate_exp(claims, leeway=0):
"""Validates that the 'exp' claim is valid.
The "exp" (expiration time) claim identifies the expiration time on
or after which the JWT MUST NOT be accepted for processing. The
processing of the "exp" claim requires that the current date/time
MUST be before the expiration date/time listed in the "exp" claim.
Implementers MAY provide for some small leeway, usually no more than
a few minutes, to account for clock skew. Its value MUST be a number
containing a NumericDate value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
leeway (int): The number of seconds of skew that is allowed.
"""
if 'exp' not in claims:
return
try:
exp = int(claims['exp'])
except ValueError:
raise JWTClaimsError('Expiration Time claim (exp) must be an integer.')
now = timegm(datetime.utcnow().utctimetuple())
if exp < (now - leeway):
raise ExpiredSignatureError('Signature has expired.')
def _validate_aud(claims, audience=None):
"""Validates that the 'aud' claim is valid.
The "aud" (audience) claim identifies the recipients that the JWT is
intended for. Each principal intended to process the JWT MUST
identify itself with a value in the audience claim. If the principal
processing the claim does not identify itself with a value in the
"aud" claim when this claim is present, then the JWT MUST be
rejected. In the general case, the "aud" value is an array of case-
sensitive strings, each containing a StringOrURI value. In the
special case when the JWT has one audience, the "aud" value MAY be a
single case-sensitive string containing a StringOrURI value. The
interpretation of audience values is generally application specific.
Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
audience (str): The audience that is verifying the token.
"""
if 'aud' not in claims:
# if audience:
# raise JWTError('Audience claim expected, but not in claims')
return
audience_claims = claims['aud']
if isinstance(audience_claims, string_types):
audience_claims = [audience_claims]
if not isinstance(audience_claims, list):
raise JWTClaimsError('Invalid claim format in token')
if any(not isinstance(c, string_types) for c in audience_claims):
raise JWTClaimsError('Invalid claim format in token')
if audience not in audience_claims:
raise JWTClaimsError('Invalid audience')
def _validate_iss(claims, issuer=None):
"""Validates that the 'iss' claim is valid.
The "iss" (issuer) claim identifies the principal that issued the
JWT. The processing of this claim is generally application specific.
The "iss" value is a case-sensitive string containing a StringOrURI
value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
issuer (str or iterable): Acceptable value(s) for the issuer that
signed the token.
"""
if issuer is not None:
if isinstance(issuer, string_types):
issuer = (issuer,)
if claims.get('iss') not in issuer:
raise JWTClaimsError('Invalid issuer')
def _validate_sub(claims, subject=None):
"""Validates that the 'sub' claim is valid.
The "sub" (subject) claim identifies the principal that is the
subject of the JWT. The claims in a JWT are normally statements
about the subject. The subject value MUST either be scoped to be
locally unique in the context of the issuer or be globally unique.
The processing of this claim is generally application specific. The
"sub" value is a case-sensitive string containing a StringOrURI
value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
subject (str): The subject of the token.
"""
if 'sub' not in claims:
return
if not isinstance(claims['sub'], string_types):
raise JWTClaimsError('Subject must be a string.')
if subject is not None:
if claims.get('sub') != subject:
raise JWTClaimsError('Invalid subject')
def _validate_jti(claims):
"""Validates that the 'jti' claim is valid.
The "jti" (JWT ID) claim provides a unique identifier for the JWT.
The identifier value MUST be assigned in a manner that ensures that
there is a negligible probability that the same value will be
accidentally assigned to a different data object; if the application
uses multiple issuers, collisions MUST be prevented among values
produced by different issuers as well. The "jti" claim can be used
to prevent the JWT from being replayed. The "jti" value is a case-
sensitive string. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
"""
if 'jti' not in claims:
return
if not isinstance(claims['jti'], string_types):
raise JWTClaimsError('JWT ID must be a string.')
def _validate_at_hash(claims, access_token, algorithm):
"""
Validates that the 'at_hash' is valid.
Its value is the base64url encoding of the left-most half of the hash
of the octets of the ASCII representation of the access_token value,
where the hash algorithm used is the hash algorithm used in the alg
Header Parameter of the ID Token's JOSE Header. For instance, if the
alg is RS256, hash the access_token value with SHA-256, then take the
left-most 128 bits and base64url encode them. The at_hash value is a
case sensitive string. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
access_token (str): The access token returned by the OpenID Provider.
algorithm (str): The algorithm used to sign the JWT, as specified by
the token headers.
"""
if 'at_hash' not in claims:
return
if not access_token:
msg = 'No access_token provided to compare against at_hash claim.'
raise JWTClaimsError(msg)
try:
expected_hash = calculate_at_hash(access_token,
ALGORITHMS.HASHES[algorithm])
except (TypeError, ValueError):
msg = 'Unable to calculate at_hash to verify against token claims.'
raise JWTClaimsError(msg)
if claims['at_hash'] != expected_hash:
raise JWTClaimsError('at_hash claim does not match access_token.')
def _validate_claims(claims, audience=None, issuer=None, subject=None,
algorithm=None, access_token=None, options=None):
leeway = options.get('leeway', 0)
if isinstance(leeway, timedelta):
leeway = timedelta_total_seconds(leeway)
for require_claim in [
e[len("require_"):] for e in options.keys() if e.startswith("require_") and options[e]
]:
if require_claim not in claims:
raise JWTError('missing required key "%s" among claims' % require_claim)
else:
options['verify_' + require_claim] = True # override verify when required
if not isinstance(audience, (string_types, type(None))):
raise JWTError('audience must be a string or None')
if options.get('verify_iat'):
_validate_iat(claims)
if options.get('verify_nbf'):
_validate_nbf(claims, leeway=leeway)
if options.get('verify_exp'):
_validate_exp(claims, leeway=leeway)
if options.get('verify_aud'):
_validate_aud(claims, audience=audience)
if options.get('verify_iss'):
_validate_iss(claims, issuer=issuer)
if options.get('verify_sub'):
_validate_sub(claims, subject=subject)
if options.get('verify_jti'):
_validate_jti(claims)
if options.get('verify_at_hash'):
_validate_at_hash(claims, access_token, algorithm)
|
mpdavis/python-jose | jose/jwt.py | _validate_nbf | python | def _validate_nbf(claims, leeway=0):
if 'nbf' not in claims:
return
try:
nbf = int(claims['nbf'])
except ValueError:
raise JWTClaimsError('Not Before claim (nbf) must be an integer.')
now = timegm(datetime.utcnow().utctimetuple())
if nbf > (now + leeway):
raise JWTClaimsError('The token is not yet valid (nbf)') | Validates that the 'nbf' claim is valid.
The "nbf" (not before) claim identifies the time before which the JWT
MUST NOT be accepted for processing. The processing of the "nbf"
claim requires that the current date/time MUST be after or equal to
the not-before date/time listed in the "nbf" claim. Implementers MAY
provide for some small leeway, usually no more than a few minutes, to
account for clock skew. Its value MUST be a number containing a
NumericDate value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
leeway (int): The number of seconds of skew that is allowed. | train | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/jwt.py#L264-L291 | null |
import json
from calendar import timegm
try:
from collections.abc import Mapping # Python3
except ImportError:
from collections import Mapping # Python2, will be depecrated in Python 3.8
from datetime import datetime
from datetime import timedelta
from six import string_types
from jose import jws
from .exceptions import JWSError
from .exceptions import JWTClaimsError
from .exceptions import JWTError
from .exceptions import ExpiredSignatureError
from .constants import ALGORITHMS
from .utils import timedelta_total_seconds, calculate_at_hash
def encode(claims, key, algorithm=ALGORITHMS.HS256, headers=None, access_token=None):
"""Encodes a claims set and returns a JWT string.
JWTs are JWS signed objects with a few reserved claims.
Args:
claims (dict): A claims set to sign
key (str or dict): The key to use for signing the claim set. Can be
individual JWK or JWK set.
algorithm (str, optional): The algorithm to use for signing the
the claims. Defaults to HS256.
headers (dict, optional): A set of headers that will be added to
the default headers. Any headers that are added as additional
headers will override the default headers.
access_token (str, optional): If present, the 'at_hash' claim will
be calculated and added to the claims present in the 'claims'
parameter.
Returns:
str: The string representation of the header, claims, and signature.
Raises:
JWTError: If there is an error encoding the claims.
Examples:
>>> jwt.encode({'a': 'b'}, 'secret', algorithm='HS256')
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
"""
for time_claim in ['exp', 'iat', 'nbf']:
# Convert datetime to a intDate value in known time-format claims
if isinstance(claims.get(time_claim), datetime):
claims[time_claim] = timegm(claims[time_claim].utctimetuple())
if access_token:
claims['at_hash'] = calculate_at_hash(access_token,
ALGORITHMS.HASHES[algorithm])
return jws.sign(claims, key, headers=headers, algorithm=algorithm)
def decode(token, key, algorithms=None, options=None, audience=None,
issuer=None, subject=None, access_token=None):
"""Verifies a JWT string's signature and validates reserved claims.
Args:
token (str): A signed JWS to be verified.
key (str or dict): A key to attempt to verify the payload with. Can be
individual JWK or JWK set.
algorithms (str or list): Valid algorithms that should be used to verify the JWS.
audience (str): The intended audience of the token. If the "aud" claim is
included in the claim set, then the audience must be included and must equal
the provided claim.
issuer (str or iterable): Acceptable value(s) for the issuer of the token.
If the "iss" claim is included in the claim set, then the issuer must be
given and the claim in the token must be among the acceptable values.
subject (str): The subject of the token. If the "sub" claim is
included in the claim set, then the subject must be included and must equal
the provided claim.
access_token (str): An access token string. If the "at_hash" claim is included in the
claim set, then the access_token must be included, and it must match
the "at_hash" claim.
options (dict): A dictionary of options for skipping validation steps.
defaults = {
'verify_signature': True,
'verify_aud': True,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': True,
'verify_jti': True,
'verify_at_hash': True,
'require_aud': False,
'require_iat': False,
'require_exp': False,
'require_nbf': False,
'require_iss': False,
'require_sub': False,
'require_jti': False,
'require_at_hash': False,
'leeway': 0,
}
Returns:
dict: The dict representation of the claims set, assuming the signature is valid
and all requested data validation passes.
Raises:
JWTError: If the signature is invalid in any way.
ExpiredSignatureError: If the signature has expired.
JWTClaimsError: If any claim is invalid in any way.
Examples:
>>> payload = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
>>> jwt.decode(payload, 'secret', algorithms='HS256')
"""
defaults = {
'verify_signature': True,
'verify_aud': True,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': True,
'verify_jti': True,
'verify_at_hash': True,
'require_aud': False,
'require_iat': False,
'require_exp': False,
'require_nbf': False,
'require_iss': False,
'require_sub': False,
'require_jti': False,
'require_at_hash': False,
'leeway': 0,
}
if options:
defaults.update(options)
verify_signature = defaults.get('verify_signature', True)
try:
payload = jws.verify(token, key, algorithms, verify=verify_signature)
except JWSError as e:
raise JWTError(e)
# Needed for at_hash verification
algorithm = jws.get_unverified_header(token)['alg']
try:
claims = json.loads(payload.decode('utf-8'))
except ValueError as e:
raise JWTError('Invalid payload string: %s' % e)
if not isinstance(claims, Mapping):
raise JWTError('Invalid payload string: must be a json object')
_validate_claims(claims, audience=audience, issuer=issuer,
subject=subject, algorithm=algorithm,
access_token=access_token,
options=defaults)
return claims
def get_unverified_header(token):
"""Returns the decoded headers without verification of any kind.
Args:
token (str): A signed JWT to decode the headers from.
Returns:
dict: The dict representation of the token headers.
Raises:
JWTError: If there is an exception decoding the token.
"""
try:
headers = jws.get_unverified_headers(token)
except Exception:
raise JWTError('Error decoding token headers.')
return headers
def get_unverified_headers(token):
"""Returns the decoded headers without verification of any kind.
This is simply a wrapper of get_unverified_header() for backwards
compatibility.
Args:
token (str): A signed JWT to decode the headers from.
Returns:
dict: The dict representation of the token headers.
Raises:
JWTError: If there is an exception decoding the token.
"""
return get_unverified_header(token)
def get_unverified_claims(token):
"""Returns the decoded claims without verification of any kind.
Args:
token (str): A signed JWT to decode the headers from.
Returns:
dict: The dict representation of the token claims.
Raises:
JWTError: If there is an exception decoding the token.
"""
try:
claims = jws.get_unverified_claims(token)
except Exception:
raise JWTError('Error decoding token claims.')
try:
claims = json.loads(claims.decode('utf-8'))
except ValueError as e:
raise JWTError('Invalid claims string: %s' % e)
if not isinstance(claims, Mapping):
raise JWTError('Invalid claims string: must be a json object')
return claims
def _validate_iat(claims):
"""Validates that the 'iat' claim is valid.
The "iat" (issued at) claim identifies the time at which the JWT was
issued. This claim can be used to determine the age of the JWT. Its
value MUST be a number containing a NumericDate value. Use of this
claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
"""
if 'iat' not in claims:
return
try:
int(claims['iat'])
except ValueError:
raise JWTClaimsError('Issued At claim (iat) must be an integer.')
def _validate_exp(claims, leeway=0):
"""Validates that the 'exp' claim is valid.
The "exp" (expiration time) claim identifies the expiration time on
or after which the JWT MUST NOT be accepted for processing. The
processing of the "exp" claim requires that the current date/time
MUST be before the expiration date/time listed in the "exp" claim.
Implementers MAY provide for some small leeway, usually no more than
a few minutes, to account for clock skew. Its value MUST be a number
containing a NumericDate value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
leeway (int): The number of seconds of skew that is allowed.
"""
if 'exp' not in claims:
return
try:
exp = int(claims['exp'])
except ValueError:
raise JWTClaimsError('Expiration Time claim (exp) must be an integer.')
now = timegm(datetime.utcnow().utctimetuple())
if exp < (now - leeway):
raise ExpiredSignatureError('Signature has expired.')
def _validate_aud(claims, audience=None):
"""Validates that the 'aud' claim is valid.
The "aud" (audience) claim identifies the recipients that the JWT is
intended for. Each principal intended to process the JWT MUST
identify itself with a value in the audience claim. If the principal
processing the claim does not identify itself with a value in the
"aud" claim when this claim is present, then the JWT MUST be
rejected. In the general case, the "aud" value is an array of case-
sensitive strings, each containing a StringOrURI value. In the
special case when the JWT has one audience, the "aud" value MAY be a
single case-sensitive string containing a StringOrURI value. The
interpretation of audience values is generally application specific.
Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
audience (str): The audience that is verifying the token.
"""
if 'aud' not in claims:
# if audience:
# raise JWTError('Audience claim expected, but not in claims')
return
audience_claims = claims['aud']
if isinstance(audience_claims, string_types):
audience_claims = [audience_claims]
if not isinstance(audience_claims, list):
raise JWTClaimsError('Invalid claim format in token')
if any(not isinstance(c, string_types) for c in audience_claims):
raise JWTClaimsError('Invalid claim format in token')
if audience not in audience_claims:
raise JWTClaimsError('Invalid audience')
def _validate_iss(claims, issuer=None):
"""Validates that the 'iss' claim is valid.
The "iss" (issuer) claim identifies the principal that issued the
JWT. The processing of this claim is generally application specific.
The "iss" value is a case-sensitive string containing a StringOrURI
value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
issuer (str or iterable): Acceptable value(s) for the issuer that
signed the token.
"""
if issuer is not None:
if isinstance(issuer, string_types):
issuer = (issuer,)
if claims.get('iss') not in issuer:
raise JWTClaimsError('Invalid issuer')
def _validate_sub(claims, subject=None):
"""Validates that the 'sub' claim is valid.
The "sub" (subject) claim identifies the principal that is the
subject of the JWT. The claims in a JWT are normally statements
about the subject. The subject value MUST either be scoped to be
locally unique in the context of the issuer or be globally unique.
The processing of this claim is generally application specific. The
"sub" value is a case-sensitive string containing a StringOrURI
value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
subject (str): The subject of the token.
"""
if 'sub' not in claims:
return
if not isinstance(claims['sub'], string_types):
raise JWTClaimsError('Subject must be a string.')
if subject is not None:
if claims.get('sub') != subject:
raise JWTClaimsError('Invalid subject')
def _validate_jti(claims):
"""Validates that the 'jti' claim is valid.
The "jti" (JWT ID) claim provides a unique identifier for the JWT.
The identifier value MUST be assigned in a manner that ensures that
there is a negligible probability that the same value will be
accidentally assigned to a different data object; if the application
uses multiple issuers, collisions MUST be prevented among values
produced by different issuers as well. The "jti" claim can be used
to prevent the JWT from being replayed. The "jti" value is a case-
sensitive string. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
"""
if 'jti' not in claims:
return
if not isinstance(claims['jti'], string_types):
raise JWTClaimsError('JWT ID must be a string.')
def _validate_at_hash(claims, access_token, algorithm):
"""
Validates that the 'at_hash' is valid.
Its value is the base64url encoding of the left-most half of the hash
of the octets of the ASCII representation of the access_token value,
where the hash algorithm used is the hash algorithm used in the alg
Header Parameter of the ID Token's JOSE Header. For instance, if the
alg is RS256, hash the access_token value with SHA-256, then take the
left-most 128 bits and base64url encode them. The at_hash value is a
case sensitive string. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
access_token (str): The access token returned by the OpenID Provider.
algorithm (str): The algorithm used to sign the JWT, as specified by
the token headers.
"""
if 'at_hash' not in claims:
return
if not access_token:
msg = 'No access_token provided to compare against at_hash claim.'
raise JWTClaimsError(msg)
try:
expected_hash = calculate_at_hash(access_token,
ALGORITHMS.HASHES[algorithm])
except (TypeError, ValueError):
msg = 'Unable to calculate at_hash to verify against token claims.'
raise JWTClaimsError(msg)
if claims['at_hash'] != expected_hash:
raise JWTClaimsError('at_hash claim does not match access_token.')
def _validate_claims(claims, audience=None, issuer=None, subject=None,
algorithm=None, access_token=None, options=None):
leeway = options.get('leeway', 0)
if isinstance(leeway, timedelta):
leeway = timedelta_total_seconds(leeway)
for require_claim in [
e[len("require_"):] for e in options.keys() if e.startswith("require_") and options[e]
]:
if require_claim not in claims:
raise JWTError('missing required key "%s" among claims' % require_claim)
else:
options['verify_' + require_claim] = True # override verify when required
if not isinstance(audience, (string_types, type(None))):
raise JWTError('audience must be a string or None')
if options.get('verify_iat'):
_validate_iat(claims)
if options.get('verify_nbf'):
_validate_nbf(claims, leeway=leeway)
if options.get('verify_exp'):
_validate_exp(claims, leeway=leeway)
if options.get('verify_aud'):
_validate_aud(claims, audience=audience)
if options.get('verify_iss'):
_validate_iss(claims, issuer=issuer)
if options.get('verify_sub'):
_validate_sub(claims, subject=subject)
if options.get('verify_jti'):
_validate_jti(claims)
if options.get('verify_at_hash'):
_validate_at_hash(claims, access_token, algorithm)
|
mpdavis/python-jose | jose/jwt.py | _validate_exp | python | def _validate_exp(claims, leeway=0):
if 'exp' not in claims:
return
try:
exp = int(claims['exp'])
except ValueError:
raise JWTClaimsError('Expiration Time claim (exp) must be an integer.')
now = timegm(datetime.utcnow().utctimetuple())
if exp < (now - leeway):
raise ExpiredSignatureError('Signature has expired.') | Validates that the 'exp' claim is valid.
The "exp" (expiration time) claim identifies the expiration time on
or after which the JWT MUST NOT be accepted for processing. The
processing of the "exp" claim requires that the current date/time
MUST be before the expiration date/time listed in the "exp" claim.
Implementers MAY provide for some small leeway, usually no more than
a few minutes, to account for clock skew. Its value MUST be a number
containing a NumericDate value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
leeway (int): The number of seconds of skew that is allowed. | train | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/jwt.py#L294-L321 | null |
import json
from calendar import timegm
try:
from collections.abc import Mapping # Python3
except ImportError:
from collections import Mapping # Python2, will be depecrated in Python 3.8
from datetime import datetime
from datetime import timedelta
from six import string_types
from jose import jws
from .exceptions import JWSError
from .exceptions import JWTClaimsError
from .exceptions import JWTError
from .exceptions import ExpiredSignatureError
from .constants import ALGORITHMS
from .utils import timedelta_total_seconds, calculate_at_hash
def encode(claims, key, algorithm=ALGORITHMS.HS256, headers=None, access_token=None):
"""Encodes a claims set and returns a JWT string.
JWTs are JWS signed objects with a few reserved claims.
Args:
claims (dict): A claims set to sign
key (str or dict): The key to use for signing the claim set. Can be
individual JWK or JWK set.
algorithm (str, optional): The algorithm to use for signing the
the claims. Defaults to HS256.
headers (dict, optional): A set of headers that will be added to
the default headers. Any headers that are added as additional
headers will override the default headers.
access_token (str, optional): If present, the 'at_hash' claim will
be calculated and added to the claims present in the 'claims'
parameter.
Returns:
str: The string representation of the header, claims, and signature.
Raises:
JWTError: If there is an error encoding the claims.
Examples:
>>> jwt.encode({'a': 'b'}, 'secret', algorithm='HS256')
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
"""
for time_claim in ['exp', 'iat', 'nbf']:
# Convert datetime to a intDate value in known time-format claims
if isinstance(claims.get(time_claim), datetime):
claims[time_claim] = timegm(claims[time_claim].utctimetuple())
if access_token:
claims['at_hash'] = calculate_at_hash(access_token,
ALGORITHMS.HASHES[algorithm])
return jws.sign(claims, key, headers=headers, algorithm=algorithm)
def decode(token, key, algorithms=None, options=None, audience=None,
issuer=None, subject=None, access_token=None):
"""Verifies a JWT string's signature and validates reserved claims.
Args:
token (str): A signed JWS to be verified.
key (str or dict): A key to attempt to verify the payload with. Can be
individual JWK or JWK set.
algorithms (str or list): Valid algorithms that should be used to verify the JWS.
audience (str): The intended audience of the token. If the "aud" claim is
included in the claim set, then the audience must be included and must equal
the provided claim.
issuer (str or iterable): Acceptable value(s) for the issuer of the token.
If the "iss" claim is included in the claim set, then the issuer must be
given and the claim in the token must be among the acceptable values.
subject (str): The subject of the token. If the "sub" claim is
included in the claim set, then the subject must be included and must equal
the provided claim.
access_token (str): An access token string. If the "at_hash" claim is included in the
claim set, then the access_token must be included, and it must match
the "at_hash" claim.
options (dict): A dictionary of options for skipping validation steps.
defaults = {
'verify_signature': True,
'verify_aud': True,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': True,
'verify_jti': True,
'verify_at_hash': True,
'require_aud': False,
'require_iat': False,
'require_exp': False,
'require_nbf': False,
'require_iss': False,
'require_sub': False,
'require_jti': False,
'require_at_hash': False,
'leeway': 0,
}
Returns:
dict: The dict representation of the claims set, assuming the signature is valid
and all requested data validation passes.
Raises:
JWTError: If the signature is invalid in any way.
ExpiredSignatureError: If the signature has expired.
JWTClaimsError: If any claim is invalid in any way.
Examples:
>>> payload = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
>>> jwt.decode(payload, 'secret', algorithms='HS256')
"""
defaults = {
'verify_signature': True,
'verify_aud': True,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': True,
'verify_jti': True,
'verify_at_hash': True,
'require_aud': False,
'require_iat': False,
'require_exp': False,
'require_nbf': False,
'require_iss': False,
'require_sub': False,
'require_jti': False,
'require_at_hash': False,
'leeway': 0,
}
if options:
defaults.update(options)
verify_signature = defaults.get('verify_signature', True)
try:
payload = jws.verify(token, key, algorithms, verify=verify_signature)
except JWSError as e:
raise JWTError(e)
# Needed for at_hash verification
algorithm = jws.get_unverified_header(token)['alg']
try:
claims = json.loads(payload.decode('utf-8'))
except ValueError as e:
raise JWTError('Invalid payload string: %s' % e)
if not isinstance(claims, Mapping):
raise JWTError('Invalid payload string: must be a json object')
_validate_claims(claims, audience=audience, issuer=issuer,
subject=subject, algorithm=algorithm,
access_token=access_token,
options=defaults)
return claims
def get_unverified_header(token):
"""Returns the decoded headers without verification of any kind.
Args:
token (str): A signed JWT to decode the headers from.
Returns:
dict: The dict representation of the token headers.
Raises:
JWTError: If there is an exception decoding the token.
"""
try:
headers = jws.get_unverified_headers(token)
except Exception:
raise JWTError('Error decoding token headers.')
return headers
def get_unverified_headers(token):
"""Returns the decoded headers without verification of any kind.
This is simply a wrapper of get_unverified_header() for backwards
compatibility.
Args:
token (str): A signed JWT to decode the headers from.
Returns:
dict: The dict representation of the token headers.
Raises:
JWTError: If there is an exception decoding the token.
"""
return get_unverified_header(token)
def get_unverified_claims(token):
"""Returns the decoded claims without verification of any kind.
Args:
token (str): A signed JWT to decode the headers from.
Returns:
dict: The dict representation of the token claims.
Raises:
JWTError: If there is an exception decoding the token.
"""
try:
claims = jws.get_unverified_claims(token)
except Exception:
raise JWTError('Error decoding token claims.')
try:
claims = json.loads(claims.decode('utf-8'))
except ValueError as e:
raise JWTError('Invalid claims string: %s' % e)
if not isinstance(claims, Mapping):
raise JWTError('Invalid claims string: must be a json object')
return claims
def _validate_iat(claims):
"""Validates that the 'iat' claim is valid.
The "iat" (issued at) claim identifies the time at which the JWT was
issued. This claim can be used to determine the age of the JWT. Its
value MUST be a number containing a NumericDate value. Use of this
claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
"""
if 'iat' not in claims:
return
try:
int(claims['iat'])
except ValueError:
raise JWTClaimsError('Issued At claim (iat) must be an integer.')
def _validate_nbf(claims, leeway=0):
"""Validates that the 'nbf' claim is valid.
The "nbf" (not before) claim identifies the time before which the JWT
MUST NOT be accepted for processing. The processing of the "nbf"
claim requires that the current date/time MUST be after or equal to
the not-before date/time listed in the "nbf" claim. Implementers MAY
provide for some small leeway, usually no more than a few minutes, to
account for clock skew. Its value MUST be a number containing a
NumericDate value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
leeway (int): The number of seconds of skew that is allowed.
"""
if 'nbf' not in claims:
return
try:
nbf = int(claims['nbf'])
except ValueError:
raise JWTClaimsError('Not Before claim (nbf) must be an integer.')
now = timegm(datetime.utcnow().utctimetuple())
if nbf > (now + leeway):
raise JWTClaimsError('The token is not yet valid (nbf)')
def _validate_aud(claims, audience=None):
"""Validates that the 'aud' claim is valid.
The "aud" (audience) claim identifies the recipients that the JWT is
intended for. Each principal intended to process the JWT MUST
identify itself with a value in the audience claim. If the principal
processing the claim does not identify itself with a value in the
"aud" claim when this claim is present, then the JWT MUST be
rejected. In the general case, the "aud" value is an array of case-
sensitive strings, each containing a StringOrURI value. In the
special case when the JWT has one audience, the "aud" value MAY be a
single case-sensitive string containing a StringOrURI value. The
interpretation of audience values is generally application specific.
Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
audience (str): The audience that is verifying the token.
"""
if 'aud' not in claims:
# if audience:
# raise JWTError('Audience claim expected, but not in claims')
return
audience_claims = claims['aud']
if isinstance(audience_claims, string_types):
audience_claims = [audience_claims]
if not isinstance(audience_claims, list):
raise JWTClaimsError('Invalid claim format in token')
if any(not isinstance(c, string_types) for c in audience_claims):
raise JWTClaimsError('Invalid claim format in token')
if audience not in audience_claims:
raise JWTClaimsError('Invalid audience')
def _validate_iss(claims, issuer=None):
"""Validates that the 'iss' claim is valid.
The "iss" (issuer) claim identifies the principal that issued the
JWT. The processing of this claim is generally application specific.
The "iss" value is a case-sensitive string containing a StringOrURI
value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
issuer (str or iterable): Acceptable value(s) for the issuer that
signed the token.
"""
if issuer is not None:
if isinstance(issuer, string_types):
issuer = (issuer,)
if claims.get('iss') not in issuer:
raise JWTClaimsError('Invalid issuer')
def _validate_sub(claims, subject=None):
"""Validates that the 'sub' claim is valid.
The "sub" (subject) claim identifies the principal that is the
subject of the JWT. The claims in a JWT are normally statements
about the subject. The subject value MUST either be scoped to be
locally unique in the context of the issuer or be globally unique.
The processing of this claim is generally application specific. The
"sub" value is a case-sensitive string containing a StringOrURI
value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
subject (str): The subject of the token.
"""
if 'sub' not in claims:
return
if not isinstance(claims['sub'], string_types):
raise JWTClaimsError('Subject must be a string.')
if subject is not None:
if claims.get('sub') != subject:
raise JWTClaimsError('Invalid subject')
def _validate_jti(claims):
"""Validates that the 'jti' claim is valid.
The "jti" (JWT ID) claim provides a unique identifier for the JWT.
The identifier value MUST be assigned in a manner that ensures that
there is a negligible probability that the same value will be
accidentally assigned to a different data object; if the application
uses multiple issuers, collisions MUST be prevented among values
produced by different issuers as well. The "jti" claim can be used
to prevent the JWT from being replayed. The "jti" value is a case-
sensitive string. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
"""
if 'jti' not in claims:
return
if not isinstance(claims['jti'], string_types):
raise JWTClaimsError('JWT ID must be a string.')
def _validate_at_hash(claims, access_token, algorithm):
"""
Validates that the 'at_hash' is valid.
Its value is the base64url encoding of the left-most half of the hash
of the octets of the ASCII representation of the access_token value,
where the hash algorithm used is the hash algorithm used in the alg
Header Parameter of the ID Token's JOSE Header. For instance, if the
alg is RS256, hash the access_token value with SHA-256, then take the
left-most 128 bits and base64url encode them. The at_hash value is a
case sensitive string. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
access_token (str): The access token returned by the OpenID Provider.
algorithm (str): The algorithm used to sign the JWT, as specified by
the token headers.
"""
if 'at_hash' not in claims:
return
if not access_token:
msg = 'No access_token provided to compare against at_hash claim.'
raise JWTClaimsError(msg)
try:
expected_hash = calculate_at_hash(access_token,
ALGORITHMS.HASHES[algorithm])
except (TypeError, ValueError):
msg = 'Unable to calculate at_hash to verify against token claims.'
raise JWTClaimsError(msg)
if claims['at_hash'] != expected_hash:
raise JWTClaimsError('at_hash claim does not match access_token.')
def _validate_claims(claims, audience=None, issuer=None, subject=None,
algorithm=None, access_token=None, options=None):
leeway = options.get('leeway', 0)
if isinstance(leeway, timedelta):
leeway = timedelta_total_seconds(leeway)
for require_claim in [
e[len("require_"):] for e in options.keys() if e.startswith("require_") and options[e]
]:
if require_claim not in claims:
raise JWTError('missing required key "%s" among claims' % require_claim)
else:
options['verify_' + require_claim] = True # override verify when required
if not isinstance(audience, (string_types, type(None))):
raise JWTError('audience must be a string or None')
if options.get('verify_iat'):
_validate_iat(claims)
if options.get('verify_nbf'):
_validate_nbf(claims, leeway=leeway)
if options.get('verify_exp'):
_validate_exp(claims, leeway=leeway)
if options.get('verify_aud'):
_validate_aud(claims, audience=audience)
if options.get('verify_iss'):
_validate_iss(claims, issuer=issuer)
if options.get('verify_sub'):
_validate_sub(claims, subject=subject)
if options.get('verify_jti'):
_validate_jti(claims)
if options.get('verify_at_hash'):
_validate_at_hash(claims, access_token, algorithm)
|
mpdavis/python-jose | jose/jwt.py | _validate_aud | python | def _validate_aud(claims, audience=None):
if 'aud' not in claims:
# if audience:
# raise JWTError('Audience claim expected, but not in claims')
return
audience_claims = claims['aud']
if isinstance(audience_claims, string_types):
audience_claims = [audience_claims]
if not isinstance(audience_claims, list):
raise JWTClaimsError('Invalid claim format in token')
if any(not isinstance(c, string_types) for c in audience_claims):
raise JWTClaimsError('Invalid claim format in token')
if audience not in audience_claims:
raise JWTClaimsError('Invalid audience') | Validates that the 'aud' claim is valid.
The "aud" (audience) claim identifies the recipients that the JWT is
intended for. Each principal intended to process the JWT MUST
identify itself with a value in the audience claim. If the principal
processing the claim does not identify itself with a value in the
"aud" claim when this claim is present, then the JWT MUST be
rejected. In the general case, the "aud" value is an array of case-
sensitive strings, each containing a StringOrURI value. In the
special case when the JWT has one audience, the "aud" value MAY be a
single case-sensitive string containing a StringOrURI value. The
interpretation of audience values is generally application specific.
Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
audience (str): The audience that is verifying the token. | train | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/jwt.py#L324-L357 | null |
import json
from calendar import timegm
try:
from collections.abc import Mapping # Python3
except ImportError:
from collections import Mapping # Python2, will be depecrated in Python 3.8
from datetime import datetime
from datetime import timedelta
from six import string_types
from jose import jws
from .exceptions import JWSError
from .exceptions import JWTClaimsError
from .exceptions import JWTError
from .exceptions import ExpiredSignatureError
from .constants import ALGORITHMS
from .utils import timedelta_total_seconds, calculate_at_hash
def encode(claims, key, algorithm=ALGORITHMS.HS256, headers=None, access_token=None):
"""Encodes a claims set and returns a JWT string.
JWTs are JWS signed objects with a few reserved claims.
Args:
claims (dict): A claims set to sign
key (str or dict): The key to use for signing the claim set. Can be
individual JWK or JWK set.
algorithm (str, optional): The algorithm to use for signing the
the claims. Defaults to HS256.
headers (dict, optional): A set of headers that will be added to
the default headers. Any headers that are added as additional
headers will override the default headers.
access_token (str, optional): If present, the 'at_hash' claim will
be calculated and added to the claims present in the 'claims'
parameter.
Returns:
str: The string representation of the header, claims, and signature.
Raises:
JWTError: If there is an error encoding the claims.
Examples:
>>> jwt.encode({'a': 'b'}, 'secret', algorithm='HS256')
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
"""
for time_claim in ['exp', 'iat', 'nbf']:
# Convert datetime to a intDate value in known time-format claims
if isinstance(claims.get(time_claim), datetime):
claims[time_claim] = timegm(claims[time_claim].utctimetuple())
if access_token:
claims['at_hash'] = calculate_at_hash(access_token,
ALGORITHMS.HASHES[algorithm])
return jws.sign(claims, key, headers=headers, algorithm=algorithm)
def decode(token, key, algorithms=None, options=None, audience=None,
issuer=None, subject=None, access_token=None):
"""Verifies a JWT string's signature and validates reserved claims.
Args:
token (str): A signed JWS to be verified.
key (str or dict): A key to attempt to verify the payload with. Can be
individual JWK or JWK set.
algorithms (str or list): Valid algorithms that should be used to verify the JWS.
audience (str): The intended audience of the token. If the "aud" claim is
included in the claim set, then the audience must be included and must equal
the provided claim.
issuer (str or iterable): Acceptable value(s) for the issuer of the token.
If the "iss" claim is included in the claim set, then the issuer must be
given and the claim in the token must be among the acceptable values.
subject (str): The subject of the token. If the "sub" claim is
included in the claim set, then the subject must be included and must equal
the provided claim.
access_token (str): An access token string. If the "at_hash" claim is included in the
claim set, then the access_token must be included, and it must match
the "at_hash" claim.
options (dict): A dictionary of options for skipping validation steps.
defaults = {
'verify_signature': True,
'verify_aud': True,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': True,
'verify_jti': True,
'verify_at_hash': True,
'require_aud': False,
'require_iat': False,
'require_exp': False,
'require_nbf': False,
'require_iss': False,
'require_sub': False,
'require_jti': False,
'require_at_hash': False,
'leeway': 0,
}
Returns:
dict: The dict representation of the claims set, assuming the signature is valid
and all requested data validation passes.
Raises:
JWTError: If the signature is invalid in any way.
ExpiredSignatureError: If the signature has expired.
JWTClaimsError: If any claim is invalid in any way.
Examples:
>>> payload = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
>>> jwt.decode(payload, 'secret', algorithms='HS256')
"""
defaults = {
'verify_signature': True,
'verify_aud': True,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': True,
'verify_jti': True,
'verify_at_hash': True,
'require_aud': False,
'require_iat': False,
'require_exp': False,
'require_nbf': False,
'require_iss': False,
'require_sub': False,
'require_jti': False,
'require_at_hash': False,
'leeway': 0,
}
if options:
defaults.update(options)
verify_signature = defaults.get('verify_signature', True)
try:
payload = jws.verify(token, key, algorithms, verify=verify_signature)
except JWSError as e:
raise JWTError(e)
# Needed for at_hash verification
algorithm = jws.get_unverified_header(token)['alg']
try:
claims = json.loads(payload.decode('utf-8'))
except ValueError as e:
raise JWTError('Invalid payload string: %s' % e)
if not isinstance(claims, Mapping):
raise JWTError('Invalid payload string: must be a json object')
_validate_claims(claims, audience=audience, issuer=issuer,
subject=subject, algorithm=algorithm,
access_token=access_token,
options=defaults)
return claims
def get_unverified_header(token):
"""Returns the decoded headers without verification of any kind.
Args:
token (str): A signed JWT to decode the headers from.
Returns:
dict: The dict representation of the token headers.
Raises:
JWTError: If there is an exception decoding the token.
"""
try:
headers = jws.get_unverified_headers(token)
except Exception:
raise JWTError('Error decoding token headers.')
return headers
def get_unverified_headers(token):
"""Returns the decoded headers without verification of any kind.
This is simply a wrapper of get_unverified_header() for backwards
compatibility.
Args:
token (str): A signed JWT to decode the headers from.
Returns:
dict: The dict representation of the token headers.
Raises:
JWTError: If there is an exception decoding the token.
"""
return get_unverified_header(token)
def get_unverified_claims(token):
"""Returns the decoded claims without verification of any kind.
Args:
token (str): A signed JWT to decode the headers from.
Returns:
dict: The dict representation of the token claims.
Raises:
JWTError: If there is an exception decoding the token.
"""
try:
claims = jws.get_unverified_claims(token)
except Exception:
raise JWTError('Error decoding token claims.')
try:
claims = json.loads(claims.decode('utf-8'))
except ValueError as e:
raise JWTError('Invalid claims string: %s' % e)
if not isinstance(claims, Mapping):
raise JWTError('Invalid claims string: must be a json object')
return claims
def _validate_iat(claims):
"""Validates that the 'iat' claim is valid.
The "iat" (issued at) claim identifies the time at which the JWT was
issued. This claim can be used to determine the age of the JWT. Its
value MUST be a number containing a NumericDate value. Use of this
claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
"""
if 'iat' not in claims:
return
try:
int(claims['iat'])
except ValueError:
raise JWTClaimsError('Issued At claim (iat) must be an integer.')
def _validate_nbf(claims, leeway=0):
"""Validates that the 'nbf' claim is valid.
The "nbf" (not before) claim identifies the time before which the JWT
MUST NOT be accepted for processing. The processing of the "nbf"
claim requires that the current date/time MUST be after or equal to
the not-before date/time listed in the "nbf" claim. Implementers MAY
provide for some small leeway, usually no more than a few minutes, to
account for clock skew. Its value MUST be a number containing a
NumericDate value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
leeway (int): The number of seconds of skew that is allowed.
"""
if 'nbf' not in claims:
return
try:
nbf = int(claims['nbf'])
except ValueError:
raise JWTClaimsError('Not Before claim (nbf) must be an integer.')
now = timegm(datetime.utcnow().utctimetuple())
if nbf > (now + leeway):
raise JWTClaimsError('The token is not yet valid (nbf)')
def _validate_exp(claims, leeway=0):
"""Validates that the 'exp' claim is valid.
The "exp" (expiration time) claim identifies the expiration time on
or after which the JWT MUST NOT be accepted for processing. The
processing of the "exp" claim requires that the current date/time
MUST be before the expiration date/time listed in the "exp" claim.
Implementers MAY provide for some small leeway, usually no more than
a few minutes, to account for clock skew. Its value MUST be a number
containing a NumericDate value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
leeway (int): The number of seconds of skew that is allowed.
"""
if 'exp' not in claims:
return
try:
exp = int(claims['exp'])
except ValueError:
raise JWTClaimsError('Expiration Time claim (exp) must be an integer.')
now = timegm(datetime.utcnow().utctimetuple())
if exp < (now - leeway):
raise ExpiredSignatureError('Signature has expired.')
def _validate_iss(claims, issuer=None):
"""Validates that the 'iss' claim is valid.
The "iss" (issuer) claim identifies the principal that issued the
JWT. The processing of this claim is generally application specific.
The "iss" value is a case-sensitive string containing a StringOrURI
value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
issuer (str or iterable): Acceptable value(s) for the issuer that
signed the token.
"""
if issuer is not None:
if isinstance(issuer, string_types):
issuer = (issuer,)
if claims.get('iss') not in issuer:
raise JWTClaimsError('Invalid issuer')
def _validate_sub(claims, subject=None):
"""Validates that the 'sub' claim is valid.
The "sub" (subject) claim identifies the principal that is the
subject of the JWT. The claims in a JWT are normally statements
about the subject. The subject value MUST either be scoped to be
locally unique in the context of the issuer or be globally unique.
The processing of this claim is generally application specific. The
"sub" value is a case-sensitive string containing a StringOrURI
value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
subject (str): The subject of the token.
"""
if 'sub' not in claims:
return
if not isinstance(claims['sub'], string_types):
raise JWTClaimsError('Subject must be a string.')
if subject is not None:
if claims.get('sub') != subject:
raise JWTClaimsError('Invalid subject')
def _validate_jti(claims):
"""Validates that the 'jti' claim is valid.
The "jti" (JWT ID) claim provides a unique identifier for the JWT.
The identifier value MUST be assigned in a manner that ensures that
there is a negligible probability that the same value will be
accidentally assigned to a different data object; if the application
uses multiple issuers, collisions MUST be prevented among values
produced by different issuers as well. The "jti" claim can be used
to prevent the JWT from being replayed. The "jti" value is a case-
sensitive string. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
"""
if 'jti' not in claims:
return
if not isinstance(claims['jti'], string_types):
raise JWTClaimsError('JWT ID must be a string.')
def _validate_at_hash(claims, access_token, algorithm):
"""
Validates that the 'at_hash' is valid.
Its value is the base64url encoding of the left-most half of the hash
of the octets of the ASCII representation of the access_token value,
where the hash algorithm used is the hash algorithm used in the alg
Header Parameter of the ID Token's JOSE Header. For instance, if the
alg is RS256, hash the access_token value with SHA-256, then take the
left-most 128 bits and base64url encode them. The at_hash value is a
case sensitive string. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
access_token (str): The access token returned by the OpenID Provider.
algorithm (str): The algorithm used to sign the JWT, as specified by
the token headers.
"""
if 'at_hash' not in claims:
return
if not access_token:
msg = 'No access_token provided to compare against at_hash claim.'
raise JWTClaimsError(msg)
try:
expected_hash = calculate_at_hash(access_token,
ALGORITHMS.HASHES[algorithm])
except (TypeError, ValueError):
msg = 'Unable to calculate at_hash to verify against token claims.'
raise JWTClaimsError(msg)
if claims['at_hash'] != expected_hash:
raise JWTClaimsError('at_hash claim does not match access_token.')
def _validate_claims(claims, audience=None, issuer=None, subject=None,
algorithm=None, access_token=None, options=None):
leeway = options.get('leeway', 0)
if isinstance(leeway, timedelta):
leeway = timedelta_total_seconds(leeway)
for require_claim in [
e[len("require_"):] for e in options.keys() if e.startswith("require_") and options[e]
]:
if require_claim not in claims:
raise JWTError('missing required key "%s" among claims' % require_claim)
else:
options['verify_' + require_claim] = True # override verify when required
if not isinstance(audience, (string_types, type(None))):
raise JWTError('audience must be a string or None')
if options.get('verify_iat'):
_validate_iat(claims)
if options.get('verify_nbf'):
_validate_nbf(claims, leeway=leeway)
if options.get('verify_exp'):
_validate_exp(claims, leeway=leeway)
if options.get('verify_aud'):
_validate_aud(claims, audience=audience)
if options.get('verify_iss'):
_validate_iss(claims, issuer=issuer)
if options.get('verify_sub'):
_validate_sub(claims, subject=subject)
if options.get('verify_jti'):
_validate_jti(claims)
if options.get('verify_at_hash'):
_validate_at_hash(claims, access_token, algorithm)
|
mpdavis/python-jose | jose/jwt.py | _validate_iss | python | def _validate_iss(claims, issuer=None):
if issuer is not None:
if isinstance(issuer, string_types):
issuer = (issuer,)
if claims.get('iss') not in issuer:
raise JWTClaimsError('Invalid issuer') | Validates that the 'iss' claim is valid.
The "iss" (issuer) claim identifies the principal that issued the
JWT. The processing of this claim is generally application specific.
The "iss" value is a case-sensitive string containing a StringOrURI
value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
issuer (str or iterable): Acceptable value(s) for the issuer that
signed the token. | train | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/jwt.py#L360-L378 | null |
import json
from calendar import timegm
try:
from collections.abc import Mapping # Python3
except ImportError:
from collections import Mapping # Python2, will be depecrated in Python 3.8
from datetime import datetime
from datetime import timedelta
from six import string_types
from jose import jws
from .exceptions import JWSError
from .exceptions import JWTClaimsError
from .exceptions import JWTError
from .exceptions import ExpiredSignatureError
from .constants import ALGORITHMS
from .utils import timedelta_total_seconds, calculate_at_hash
def encode(claims, key, algorithm=ALGORITHMS.HS256, headers=None, access_token=None):
"""Encodes a claims set and returns a JWT string.
JWTs are JWS signed objects with a few reserved claims.
Args:
claims (dict): A claims set to sign
key (str or dict): The key to use for signing the claim set. Can be
individual JWK or JWK set.
algorithm (str, optional): The algorithm to use for signing the
the claims. Defaults to HS256.
headers (dict, optional): A set of headers that will be added to
the default headers. Any headers that are added as additional
headers will override the default headers.
access_token (str, optional): If present, the 'at_hash' claim will
be calculated and added to the claims present in the 'claims'
parameter.
Returns:
str: The string representation of the header, claims, and signature.
Raises:
JWTError: If there is an error encoding the claims.
Examples:
>>> jwt.encode({'a': 'b'}, 'secret', algorithm='HS256')
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
"""
for time_claim in ['exp', 'iat', 'nbf']:
# Convert datetime to a intDate value in known time-format claims
if isinstance(claims.get(time_claim), datetime):
claims[time_claim] = timegm(claims[time_claim].utctimetuple())
if access_token:
claims['at_hash'] = calculate_at_hash(access_token,
ALGORITHMS.HASHES[algorithm])
return jws.sign(claims, key, headers=headers, algorithm=algorithm)
def decode(token, key, algorithms=None, options=None, audience=None,
issuer=None, subject=None, access_token=None):
"""Verifies a JWT string's signature and validates reserved claims.
Args:
token (str): A signed JWS to be verified.
key (str or dict): A key to attempt to verify the payload with. Can be
individual JWK or JWK set.
algorithms (str or list): Valid algorithms that should be used to verify the JWS.
audience (str): The intended audience of the token. If the "aud" claim is
included in the claim set, then the audience must be included and must equal
the provided claim.
issuer (str or iterable): Acceptable value(s) for the issuer of the token.
If the "iss" claim is included in the claim set, then the issuer must be
given and the claim in the token must be among the acceptable values.
subject (str): The subject of the token. If the "sub" claim is
included in the claim set, then the subject must be included and must equal
the provided claim.
access_token (str): An access token string. If the "at_hash" claim is included in the
claim set, then the access_token must be included, and it must match
the "at_hash" claim.
options (dict): A dictionary of options for skipping validation steps.
defaults = {
'verify_signature': True,
'verify_aud': True,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': True,
'verify_jti': True,
'verify_at_hash': True,
'require_aud': False,
'require_iat': False,
'require_exp': False,
'require_nbf': False,
'require_iss': False,
'require_sub': False,
'require_jti': False,
'require_at_hash': False,
'leeway': 0,
}
Returns:
dict: The dict representation of the claims set, assuming the signature is valid
and all requested data validation passes.
Raises:
JWTError: If the signature is invalid in any way.
ExpiredSignatureError: If the signature has expired.
JWTClaimsError: If any claim is invalid in any way.
Examples:
>>> payload = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
>>> jwt.decode(payload, 'secret', algorithms='HS256')
"""
defaults = {
'verify_signature': True,
'verify_aud': True,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': True,
'verify_jti': True,
'verify_at_hash': True,
'require_aud': False,
'require_iat': False,
'require_exp': False,
'require_nbf': False,
'require_iss': False,
'require_sub': False,
'require_jti': False,
'require_at_hash': False,
'leeway': 0,
}
if options:
defaults.update(options)
verify_signature = defaults.get('verify_signature', True)
try:
payload = jws.verify(token, key, algorithms, verify=verify_signature)
except JWSError as e:
raise JWTError(e)
# Needed for at_hash verification
algorithm = jws.get_unverified_header(token)['alg']
try:
claims = json.loads(payload.decode('utf-8'))
except ValueError as e:
raise JWTError('Invalid payload string: %s' % e)
if not isinstance(claims, Mapping):
raise JWTError('Invalid payload string: must be a json object')
_validate_claims(claims, audience=audience, issuer=issuer,
subject=subject, algorithm=algorithm,
access_token=access_token,
options=defaults)
return claims
def get_unverified_header(token):
"""Returns the decoded headers without verification of any kind.
Args:
token (str): A signed JWT to decode the headers from.
Returns:
dict: The dict representation of the token headers.
Raises:
JWTError: If there is an exception decoding the token.
"""
try:
headers = jws.get_unverified_headers(token)
except Exception:
raise JWTError('Error decoding token headers.')
return headers
def get_unverified_headers(token):
"""Returns the decoded headers without verification of any kind.
This is simply a wrapper of get_unverified_header() for backwards
compatibility.
Args:
token (str): A signed JWT to decode the headers from.
Returns:
dict: The dict representation of the token headers.
Raises:
JWTError: If there is an exception decoding the token.
"""
return get_unverified_header(token)
def get_unverified_claims(token):
"""Returns the decoded claims without verification of any kind.
Args:
token (str): A signed JWT to decode the headers from.
Returns:
dict: The dict representation of the token claims.
Raises:
JWTError: If there is an exception decoding the token.
"""
try:
claims = jws.get_unverified_claims(token)
except Exception:
raise JWTError('Error decoding token claims.')
try:
claims = json.loads(claims.decode('utf-8'))
except ValueError as e:
raise JWTError('Invalid claims string: %s' % e)
if not isinstance(claims, Mapping):
raise JWTError('Invalid claims string: must be a json object')
return claims
def _validate_iat(claims):
"""Validates that the 'iat' claim is valid.
The "iat" (issued at) claim identifies the time at which the JWT was
issued. This claim can be used to determine the age of the JWT. Its
value MUST be a number containing a NumericDate value. Use of this
claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
"""
if 'iat' not in claims:
return
try:
int(claims['iat'])
except ValueError:
raise JWTClaimsError('Issued At claim (iat) must be an integer.')
def _validate_nbf(claims, leeway=0):
"""Validates that the 'nbf' claim is valid.
The "nbf" (not before) claim identifies the time before which the JWT
MUST NOT be accepted for processing. The processing of the "nbf"
claim requires that the current date/time MUST be after or equal to
the not-before date/time listed in the "nbf" claim. Implementers MAY
provide for some small leeway, usually no more than a few minutes, to
account for clock skew. Its value MUST be a number containing a
NumericDate value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
leeway (int): The number of seconds of skew that is allowed.
"""
if 'nbf' not in claims:
return
try:
nbf = int(claims['nbf'])
except ValueError:
raise JWTClaimsError('Not Before claim (nbf) must be an integer.')
now = timegm(datetime.utcnow().utctimetuple())
if nbf > (now + leeway):
raise JWTClaimsError('The token is not yet valid (nbf)')
def _validate_exp(claims, leeway=0):
"""Validates that the 'exp' claim is valid.
The "exp" (expiration time) claim identifies the expiration time on
or after which the JWT MUST NOT be accepted for processing. The
processing of the "exp" claim requires that the current date/time
MUST be before the expiration date/time listed in the "exp" claim.
Implementers MAY provide for some small leeway, usually no more than
a few minutes, to account for clock skew. Its value MUST be a number
containing a NumericDate value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
leeway (int): The number of seconds of skew that is allowed.
"""
if 'exp' not in claims:
return
try:
exp = int(claims['exp'])
except ValueError:
raise JWTClaimsError('Expiration Time claim (exp) must be an integer.')
now = timegm(datetime.utcnow().utctimetuple())
if exp < (now - leeway):
raise ExpiredSignatureError('Signature has expired.')
def _validate_aud(claims, audience=None):
"""Validates that the 'aud' claim is valid.
The "aud" (audience) claim identifies the recipients that the JWT is
intended for. Each principal intended to process the JWT MUST
identify itself with a value in the audience claim. If the principal
processing the claim does not identify itself with a value in the
"aud" claim when this claim is present, then the JWT MUST be
rejected. In the general case, the "aud" value is an array of case-
sensitive strings, each containing a StringOrURI value. In the
special case when the JWT has one audience, the "aud" value MAY be a
single case-sensitive string containing a StringOrURI value. The
interpretation of audience values is generally application specific.
Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
audience (str): The audience that is verifying the token.
"""
if 'aud' not in claims:
# if audience:
# raise JWTError('Audience claim expected, but not in claims')
return
audience_claims = claims['aud']
if isinstance(audience_claims, string_types):
audience_claims = [audience_claims]
if not isinstance(audience_claims, list):
raise JWTClaimsError('Invalid claim format in token')
if any(not isinstance(c, string_types) for c in audience_claims):
raise JWTClaimsError('Invalid claim format in token')
if audience not in audience_claims:
raise JWTClaimsError('Invalid audience')
def _validate_sub(claims, subject=None):
"""Validates that the 'sub' claim is valid.
The "sub" (subject) claim identifies the principal that is the
subject of the JWT. The claims in a JWT are normally statements
about the subject. The subject value MUST either be scoped to be
locally unique in the context of the issuer or be globally unique.
The processing of this claim is generally application specific. The
"sub" value is a case-sensitive string containing a StringOrURI
value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
subject (str): The subject of the token.
"""
if 'sub' not in claims:
return
if not isinstance(claims['sub'], string_types):
raise JWTClaimsError('Subject must be a string.')
if subject is not None:
if claims.get('sub') != subject:
raise JWTClaimsError('Invalid subject')
def _validate_jti(claims):
"""Validates that the 'jti' claim is valid.
The "jti" (JWT ID) claim provides a unique identifier for the JWT.
The identifier value MUST be assigned in a manner that ensures that
there is a negligible probability that the same value will be
accidentally assigned to a different data object; if the application
uses multiple issuers, collisions MUST be prevented among values
produced by different issuers as well. The "jti" claim can be used
to prevent the JWT from being replayed. The "jti" value is a case-
sensitive string. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
"""
if 'jti' not in claims:
return
if not isinstance(claims['jti'], string_types):
raise JWTClaimsError('JWT ID must be a string.')
def _validate_at_hash(claims, access_token, algorithm):
"""
Validates that the 'at_hash' is valid.
Its value is the base64url encoding of the left-most half of the hash
of the octets of the ASCII representation of the access_token value,
where the hash algorithm used is the hash algorithm used in the alg
Header Parameter of the ID Token's JOSE Header. For instance, if the
alg is RS256, hash the access_token value with SHA-256, then take the
left-most 128 bits and base64url encode them. The at_hash value is a
case sensitive string. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
access_token (str): The access token returned by the OpenID Provider.
algorithm (str): The algorithm used to sign the JWT, as specified by
the token headers.
"""
if 'at_hash' not in claims:
return
if not access_token:
msg = 'No access_token provided to compare against at_hash claim.'
raise JWTClaimsError(msg)
try:
expected_hash = calculate_at_hash(access_token,
ALGORITHMS.HASHES[algorithm])
except (TypeError, ValueError):
msg = 'Unable to calculate at_hash to verify against token claims.'
raise JWTClaimsError(msg)
if claims['at_hash'] != expected_hash:
raise JWTClaimsError('at_hash claim does not match access_token.')
def _validate_claims(claims, audience=None, issuer=None, subject=None,
algorithm=None, access_token=None, options=None):
leeway = options.get('leeway', 0)
if isinstance(leeway, timedelta):
leeway = timedelta_total_seconds(leeway)
for require_claim in [
e[len("require_"):] for e in options.keys() if e.startswith("require_") and options[e]
]:
if require_claim not in claims:
raise JWTError('missing required key "%s" among claims' % require_claim)
else:
options['verify_' + require_claim] = True # override verify when required
if not isinstance(audience, (string_types, type(None))):
raise JWTError('audience must be a string or None')
if options.get('verify_iat'):
_validate_iat(claims)
if options.get('verify_nbf'):
_validate_nbf(claims, leeway=leeway)
if options.get('verify_exp'):
_validate_exp(claims, leeway=leeway)
if options.get('verify_aud'):
_validate_aud(claims, audience=audience)
if options.get('verify_iss'):
_validate_iss(claims, issuer=issuer)
if options.get('verify_sub'):
_validate_sub(claims, subject=subject)
if options.get('verify_jti'):
_validate_jti(claims)
if options.get('verify_at_hash'):
_validate_at_hash(claims, access_token, algorithm)
|
mpdavis/python-jose | jose/jwt.py | _validate_sub | python | def _validate_sub(claims, subject=None):
if 'sub' not in claims:
return
if not isinstance(claims['sub'], string_types):
raise JWTClaimsError('Subject must be a string.')
if subject is not None:
if claims.get('sub') != subject:
raise JWTClaimsError('Invalid subject') | Validates that the 'sub' claim is valid.
The "sub" (subject) claim identifies the principal that is the
subject of the JWT. The claims in a JWT are normally statements
about the subject. The subject value MUST either be scoped to be
locally unique in the context of the issuer or be globally unique.
The processing of this claim is generally application specific. The
"sub" value is a case-sensitive string containing a StringOrURI
value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
subject (str): The subject of the token. | train | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/jwt.py#L381-L405 | null |
import json
from calendar import timegm
try:
from collections.abc import Mapping # Python3
except ImportError:
from collections import Mapping # Python2, will be depecrated in Python 3.8
from datetime import datetime
from datetime import timedelta
from six import string_types
from jose import jws
from .exceptions import JWSError
from .exceptions import JWTClaimsError
from .exceptions import JWTError
from .exceptions import ExpiredSignatureError
from .constants import ALGORITHMS
from .utils import timedelta_total_seconds, calculate_at_hash
def encode(claims, key, algorithm=ALGORITHMS.HS256, headers=None, access_token=None):
"""Encodes a claims set and returns a JWT string.
JWTs are JWS signed objects with a few reserved claims.
Args:
claims (dict): A claims set to sign
key (str or dict): The key to use for signing the claim set. Can be
individual JWK or JWK set.
algorithm (str, optional): The algorithm to use for signing the
the claims. Defaults to HS256.
headers (dict, optional): A set of headers that will be added to
the default headers. Any headers that are added as additional
headers will override the default headers.
access_token (str, optional): If present, the 'at_hash' claim will
be calculated and added to the claims present in the 'claims'
parameter.
Returns:
str: The string representation of the header, claims, and signature.
Raises:
JWTError: If there is an error encoding the claims.
Examples:
>>> jwt.encode({'a': 'b'}, 'secret', algorithm='HS256')
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
"""
for time_claim in ['exp', 'iat', 'nbf']:
# Convert datetime to a intDate value in known time-format claims
if isinstance(claims.get(time_claim), datetime):
claims[time_claim] = timegm(claims[time_claim].utctimetuple())
if access_token:
claims['at_hash'] = calculate_at_hash(access_token,
ALGORITHMS.HASHES[algorithm])
return jws.sign(claims, key, headers=headers, algorithm=algorithm)
def decode(token, key, algorithms=None, options=None, audience=None,
issuer=None, subject=None, access_token=None):
"""Verifies a JWT string's signature and validates reserved claims.
Args:
token (str): A signed JWS to be verified.
key (str or dict): A key to attempt to verify the payload with. Can be
individual JWK or JWK set.
algorithms (str or list): Valid algorithms that should be used to verify the JWS.
audience (str): The intended audience of the token. If the "aud" claim is
included in the claim set, then the audience must be included and must equal
the provided claim.
issuer (str or iterable): Acceptable value(s) for the issuer of the token.
If the "iss" claim is included in the claim set, then the issuer must be
given and the claim in the token must be among the acceptable values.
subject (str): The subject of the token. If the "sub" claim is
included in the claim set, then the subject must be included and must equal
the provided claim.
access_token (str): An access token string. If the "at_hash" claim is included in the
claim set, then the access_token must be included, and it must match
the "at_hash" claim.
options (dict): A dictionary of options for skipping validation steps.
defaults = {
'verify_signature': True,
'verify_aud': True,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': True,
'verify_jti': True,
'verify_at_hash': True,
'require_aud': False,
'require_iat': False,
'require_exp': False,
'require_nbf': False,
'require_iss': False,
'require_sub': False,
'require_jti': False,
'require_at_hash': False,
'leeway': 0,
}
Returns:
dict: The dict representation of the claims set, assuming the signature is valid
and all requested data validation passes.
Raises:
JWTError: If the signature is invalid in any way.
ExpiredSignatureError: If the signature has expired.
JWTClaimsError: If any claim is invalid in any way.
Examples:
>>> payload = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
>>> jwt.decode(payload, 'secret', algorithms='HS256')
"""
defaults = {
'verify_signature': True,
'verify_aud': True,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': True,
'verify_jti': True,
'verify_at_hash': True,
'require_aud': False,
'require_iat': False,
'require_exp': False,
'require_nbf': False,
'require_iss': False,
'require_sub': False,
'require_jti': False,
'require_at_hash': False,
'leeway': 0,
}
if options:
defaults.update(options)
verify_signature = defaults.get('verify_signature', True)
try:
payload = jws.verify(token, key, algorithms, verify=verify_signature)
except JWSError as e:
raise JWTError(e)
# Needed for at_hash verification
algorithm = jws.get_unverified_header(token)['alg']
try:
claims = json.loads(payload.decode('utf-8'))
except ValueError as e:
raise JWTError('Invalid payload string: %s' % e)
if not isinstance(claims, Mapping):
raise JWTError('Invalid payload string: must be a json object')
_validate_claims(claims, audience=audience, issuer=issuer,
subject=subject, algorithm=algorithm,
access_token=access_token,
options=defaults)
return claims
def get_unverified_header(token):
"""Returns the decoded headers without verification of any kind.
Args:
token (str): A signed JWT to decode the headers from.
Returns:
dict: The dict representation of the token headers.
Raises:
JWTError: If there is an exception decoding the token.
"""
try:
headers = jws.get_unverified_headers(token)
except Exception:
raise JWTError('Error decoding token headers.')
return headers
def get_unverified_headers(token):
"""Returns the decoded headers without verification of any kind.
This is simply a wrapper of get_unverified_header() for backwards
compatibility.
Args:
token (str): A signed JWT to decode the headers from.
Returns:
dict: The dict representation of the token headers.
Raises:
JWTError: If there is an exception decoding the token.
"""
return get_unverified_header(token)
def get_unverified_claims(token):
"""Returns the decoded claims without verification of any kind.
Args:
token (str): A signed JWT to decode the headers from.
Returns:
dict: The dict representation of the token claims.
Raises:
JWTError: If there is an exception decoding the token.
"""
try:
claims = jws.get_unverified_claims(token)
except Exception:
raise JWTError('Error decoding token claims.')
try:
claims = json.loads(claims.decode('utf-8'))
except ValueError as e:
raise JWTError('Invalid claims string: %s' % e)
if not isinstance(claims, Mapping):
raise JWTError('Invalid claims string: must be a json object')
return claims
def _validate_iat(claims):
"""Validates that the 'iat' claim is valid.
The "iat" (issued at) claim identifies the time at which the JWT was
issued. This claim can be used to determine the age of the JWT. Its
value MUST be a number containing a NumericDate value. Use of this
claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
"""
if 'iat' not in claims:
return
try:
int(claims['iat'])
except ValueError:
raise JWTClaimsError('Issued At claim (iat) must be an integer.')
def _validate_nbf(claims, leeway=0):
"""Validates that the 'nbf' claim is valid.
The "nbf" (not before) claim identifies the time before which the JWT
MUST NOT be accepted for processing. The processing of the "nbf"
claim requires that the current date/time MUST be after or equal to
the not-before date/time listed in the "nbf" claim. Implementers MAY
provide for some small leeway, usually no more than a few minutes, to
account for clock skew. Its value MUST be a number containing a
NumericDate value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
leeway (int): The number of seconds of skew that is allowed.
"""
if 'nbf' not in claims:
return
try:
nbf = int(claims['nbf'])
except ValueError:
raise JWTClaimsError('Not Before claim (nbf) must be an integer.')
now = timegm(datetime.utcnow().utctimetuple())
if nbf > (now + leeway):
raise JWTClaimsError('The token is not yet valid (nbf)')
def _validate_exp(claims, leeway=0):
"""Validates that the 'exp' claim is valid.
The "exp" (expiration time) claim identifies the expiration time on
or after which the JWT MUST NOT be accepted for processing. The
processing of the "exp" claim requires that the current date/time
MUST be before the expiration date/time listed in the "exp" claim.
Implementers MAY provide for some small leeway, usually no more than
a few minutes, to account for clock skew. Its value MUST be a number
containing a NumericDate value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
leeway (int): The number of seconds of skew that is allowed.
"""
if 'exp' not in claims:
return
try:
exp = int(claims['exp'])
except ValueError:
raise JWTClaimsError('Expiration Time claim (exp) must be an integer.')
now = timegm(datetime.utcnow().utctimetuple())
if exp < (now - leeway):
raise ExpiredSignatureError('Signature has expired.')
def _validate_aud(claims, audience=None):
"""Validates that the 'aud' claim is valid.
The "aud" (audience) claim identifies the recipients that the JWT is
intended for. Each principal intended to process the JWT MUST
identify itself with a value in the audience claim. If the principal
processing the claim does not identify itself with a value in the
"aud" claim when this claim is present, then the JWT MUST be
rejected. In the general case, the "aud" value is an array of case-
sensitive strings, each containing a StringOrURI value. In the
special case when the JWT has one audience, the "aud" value MAY be a
single case-sensitive string containing a StringOrURI value. The
interpretation of audience values is generally application specific.
Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
audience (str): The audience that is verifying the token.
"""
if 'aud' not in claims:
# if audience:
# raise JWTError('Audience claim expected, but not in claims')
return
audience_claims = claims['aud']
if isinstance(audience_claims, string_types):
audience_claims = [audience_claims]
if not isinstance(audience_claims, list):
raise JWTClaimsError('Invalid claim format in token')
if any(not isinstance(c, string_types) for c in audience_claims):
raise JWTClaimsError('Invalid claim format in token')
if audience not in audience_claims:
raise JWTClaimsError('Invalid audience')
def _validate_iss(claims, issuer=None):
"""Validates that the 'iss' claim is valid.
The "iss" (issuer) claim identifies the principal that issued the
JWT. The processing of this claim is generally application specific.
The "iss" value is a case-sensitive string containing a StringOrURI
value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
issuer (str or iterable): Acceptable value(s) for the issuer that
signed the token.
"""
if issuer is not None:
if isinstance(issuer, string_types):
issuer = (issuer,)
if claims.get('iss') not in issuer:
raise JWTClaimsError('Invalid issuer')
def _validate_jti(claims):
"""Validates that the 'jti' claim is valid.
The "jti" (JWT ID) claim provides a unique identifier for the JWT.
The identifier value MUST be assigned in a manner that ensures that
there is a negligible probability that the same value will be
accidentally assigned to a different data object; if the application
uses multiple issuers, collisions MUST be prevented among values
produced by different issuers as well. The "jti" claim can be used
to prevent the JWT from being replayed. The "jti" value is a case-
sensitive string. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
"""
if 'jti' not in claims:
return
if not isinstance(claims['jti'], string_types):
raise JWTClaimsError('JWT ID must be a string.')
def _validate_at_hash(claims, access_token, algorithm):
"""
Validates that the 'at_hash' is valid.
Its value is the base64url encoding of the left-most half of the hash
of the octets of the ASCII representation of the access_token value,
where the hash algorithm used is the hash algorithm used in the alg
Header Parameter of the ID Token's JOSE Header. For instance, if the
alg is RS256, hash the access_token value with SHA-256, then take the
left-most 128 bits and base64url encode them. The at_hash value is a
case sensitive string. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
access_token (str): The access token returned by the OpenID Provider.
algorithm (str): The algorithm used to sign the JWT, as specified by
the token headers.
"""
if 'at_hash' not in claims:
return
if not access_token:
msg = 'No access_token provided to compare against at_hash claim.'
raise JWTClaimsError(msg)
try:
expected_hash = calculate_at_hash(access_token,
ALGORITHMS.HASHES[algorithm])
except (TypeError, ValueError):
msg = 'Unable to calculate at_hash to verify against token claims.'
raise JWTClaimsError(msg)
if claims['at_hash'] != expected_hash:
raise JWTClaimsError('at_hash claim does not match access_token.')
def _validate_claims(claims, audience=None, issuer=None, subject=None,
algorithm=None, access_token=None, options=None):
leeway = options.get('leeway', 0)
if isinstance(leeway, timedelta):
leeway = timedelta_total_seconds(leeway)
for require_claim in [
e[len("require_"):] for e in options.keys() if e.startswith("require_") and options[e]
]:
if require_claim not in claims:
raise JWTError('missing required key "%s" among claims' % require_claim)
else:
options['verify_' + require_claim] = True # override verify when required
if not isinstance(audience, (string_types, type(None))):
raise JWTError('audience must be a string or None')
if options.get('verify_iat'):
_validate_iat(claims)
if options.get('verify_nbf'):
_validate_nbf(claims, leeway=leeway)
if options.get('verify_exp'):
_validate_exp(claims, leeway=leeway)
if options.get('verify_aud'):
_validate_aud(claims, audience=audience)
if options.get('verify_iss'):
_validate_iss(claims, issuer=issuer)
if options.get('verify_sub'):
_validate_sub(claims, subject=subject)
if options.get('verify_jti'):
_validate_jti(claims)
if options.get('verify_at_hash'):
_validate_at_hash(claims, access_token, algorithm)
|
mpdavis/python-jose | jose/backends/rsa_backend.py | _gcd | python | def _gcd(a, b):
while b:
a, b = b, (a % b)
return a | Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive). | train | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/backends/rsa_backend.py#L37-L45 | null | import binascii
import six
from pyasn1.error import PyAsn1Error
import rsa as pyrsa
import rsa.pem as pyrsa_pem
from jose.backends.base import Key
from jose.backends._asn1 import (
rsa_private_key_pkcs1_to_pkcs8,
rsa_private_key_pkcs8_to_pkcs1,
rsa_public_key_pkcs1_to_pkcs8,
)
from jose.constants import ALGORITHMS
from jose.exceptions import JWKError
from jose.utils import base64_to_long, long_to_base64
LEGACY_INVALID_PKCS8_RSA_HEADER = binascii.unhexlify(
"30" # sequence
"8204BD" # DER-encoded sequence contents length of 1213 bytes -- INCORRECT STATIC LENGTH
"020100" # integer: 0 -- Version
"30" # sequence
"0D" # DER-encoded sequence contents length of 13 bytes -- PrivateKeyAlgorithmIdentifier
"06092A864886F70D010101" # OID -- rsaEncryption
"0500" # NULL -- parameters
)
ASN1_SEQUENCE_ID = binascii.unhexlify("30")
RSA_ENCRYPTION_ASN1_OID = "1.2.840.113549.1.1.1"
# Functions gcd and rsa_recover_prime_factors were copied from cryptography 1.9
# to enable pure python rsa module to be in compliance with section 6.3.1 of RFC7518
# which requires only private exponent (d) for private key.
# Controls the number of iterations rsa_recover_prime_factors will perform
# to obtain the prime factors. Each iteration increments by 2 so the actual
# maximum attempts is half this number.
_MAX_RECOVERY_ATTEMPTS = 1000
def _rsa_recover_prime_factors(n, e, d):
"""
Compute factors p and q from the private exponent d. We assume that n has
no more than two factors. This function is adapted from code in PyCrypto.
"""
# See 8.2.2(i) in Handbook of Applied Cryptography.
ktot = d * e - 1
# The quantity d*e-1 is a multiple of phi(n), even,
# and can be represented as t*2^s.
t = ktot
while t % 2 == 0:
t = t // 2
# Cycle through all multiplicative inverses in Zn.
# The algorithm is non-deterministic, but there is a 50% chance
# any candidate a leads to successful factoring.
# See "Digitalized Signatures and Public Key Functions as Intractable
# as Factorization", M. Rabin, 1979
spotted = False
a = 2
while not spotted and a < _MAX_RECOVERY_ATTEMPTS:
k = t
# Cycle through all values a^{t*2^i}=a^k
while k < ktot:
cand = pow(a, k, n)
# Check if a^k is a non-trivial root of unity (mod n)
if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1:
# We have found a number such that (cand-1)(cand+1)=0 (mod n).
# Either of the terms divides n.
p = _gcd(cand + 1, n)
spotted = True
break
k *= 2
# This value was not any good... let's try another!
a += 2
if not spotted:
raise ValueError("Unable to compute factors p and q from exponent d.")
# Found !
q, r = divmod(n, p)
assert r == 0
p, q = sorted((p, q), reverse=True)
return (p, q)
def pem_to_spki(pem, fmt='PKCS8'):
key = RSAKey(pem, ALGORITHMS.RS256)
return key.to_pem(fmt)
def _legacy_private_key_pkcs8_to_pkcs1(pkcs8_key):
"""Legacy RSA private key PKCS8-to-PKCS1 conversion.
.. warning::
This is incorrect parsing and only works because the legacy PKCS1-to-PKCS8
encoding was also incorrect.
"""
# Only allow this processing if the prefix matches
# AND the following byte indicates an ASN1 sequence,
# as we would expect with the legacy encoding.
if not pkcs8_key.startswith(LEGACY_INVALID_PKCS8_RSA_HEADER + ASN1_SEQUENCE_ID):
raise ValueError("Invalid private key encoding")
return pkcs8_key[len(LEGACY_INVALID_PKCS8_RSA_HEADER):]
class RSAKey(Key):
SHA256 = 'SHA-256'
SHA384 = 'SHA-384'
SHA512 = 'SHA-512'
def __init__(self, key, algorithm):
if algorithm not in ALGORITHMS.RSA:
raise JWKError('hash_alg: %s is not a valid hash algorithm' % algorithm)
self.hash_alg = {
ALGORITHMS.RS256: self.SHA256,
ALGORITHMS.RS384: self.SHA384,
ALGORITHMS.RS512: self.SHA512
}.get(algorithm)
self._algorithm = algorithm
if isinstance(key, dict):
self._prepared_key = self._process_jwk(key)
return
if isinstance(key, (pyrsa.PublicKey, pyrsa.PrivateKey)):
self._prepared_key = key
return
if isinstance(key, six.string_types):
key = key.encode('utf-8')
if isinstance(key, six.binary_type):
try:
self._prepared_key = pyrsa.PublicKey.load_pkcs1(key)
except ValueError:
try:
self._prepared_key = pyrsa.PublicKey.load_pkcs1_openssl_pem(key)
except ValueError:
try:
self._prepared_key = pyrsa.PrivateKey.load_pkcs1(key)
except ValueError:
try:
der = pyrsa_pem.load_pem(key, b'PRIVATE KEY')
try:
pkcs1_key = rsa_private_key_pkcs8_to_pkcs1(der)
except PyAsn1Error:
# If the key was encoded using the old, invalid,
# encoding then pyasn1 will throw an error attempting
# to parse the key.
pkcs1_key = _legacy_private_key_pkcs8_to_pkcs1(der)
self._prepared_key = pyrsa.PrivateKey.load_pkcs1(pkcs1_key, format="DER")
except ValueError as e:
raise JWKError(e)
return
raise JWKError('Unable to parse an RSA_JWK from key: %s' % key)
def _process_jwk(self, jwk_dict):
if not jwk_dict.get('kty') == 'RSA':
raise JWKError("Incorrect key type. Expected: 'RSA', Recieved: %s" % jwk_dict.get('kty'))
e = base64_to_long(jwk_dict.get('e'))
n = base64_to_long(jwk_dict.get('n'))
if 'd' not in jwk_dict:
return pyrsa.PublicKey(e=e, n=n)
else:
d = base64_to_long(jwk_dict.get('d'))
extra_params = ['p', 'q', 'dp', 'dq', 'qi']
if any(k in jwk_dict for k in extra_params):
# Precomputed private key parameters are available.
if not all(k in jwk_dict for k in extra_params):
# These values must be present when 'p' is according to
# Section 6.3.2 of RFC7518, so if they are not we raise
# an error.
raise JWKError('Precomputed private key parameters are incomplete.')
p = base64_to_long(jwk_dict['p'])
q = base64_to_long(jwk_dict['q'])
return pyrsa.PrivateKey(e=e, n=n, d=d, p=p, q=q)
else:
p, q = _rsa_recover_prime_factors(n, e, d)
return pyrsa.PrivateKey(n=n, e=e, d=d, p=p, q=q)
def sign(self, msg):
return pyrsa.sign(msg, self._prepared_key, self.hash_alg)
def verify(self, msg, sig):
try:
pyrsa.verify(msg, sig, self._prepared_key)
return True
except pyrsa.pkcs1.VerificationError:
return False
def is_public(self):
return isinstance(self._prepared_key, pyrsa.PublicKey)
def public_key(self):
if isinstance(self._prepared_key, pyrsa.PublicKey):
return self
return self.__class__(pyrsa.PublicKey(n=self._prepared_key.n, e=self._prepared_key.e), self._algorithm)
def to_pem(self, pem_format='PKCS8'):
if isinstance(self._prepared_key, pyrsa.PrivateKey):
der = self._prepared_key.save_pkcs1(format='DER')
if pem_format == 'PKCS8':
pkcs8_der = rsa_private_key_pkcs1_to_pkcs8(der)
pem = pyrsa_pem.save_pem(pkcs8_der, pem_marker='PRIVATE KEY')
elif pem_format == 'PKCS1':
pem = pyrsa_pem.save_pem(der, pem_marker='RSA PRIVATE KEY')
else:
raise ValueError("Invalid pem format specified: %r" % (pem_format,))
else:
if pem_format == 'PKCS8':
pkcs1_der = self._prepared_key.save_pkcs1(format="DER")
pkcs8_der = rsa_public_key_pkcs1_to_pkcs8(pkcs1_der)
pem = pyrsa_pem.save_pem(pkcs8_der, pem_marker='PUBLIC KEY')
elif pem_format == 'PKCS1':
der = self._prepared_key.save_pkcs1(format='DER')
pem = pyrsa_pem.save_pem(der, pem_marker='RSA PUBLIC KEY')
else:
raise ValueError("Invalid pem format specified: %r" % (pem_format,))
return pem
def to_dict(self):
if not self.is_public():
public_key = self.public_key()._prepared_key
else:
public_key = self._prepared_key
data = {
'alg': self._algorithm,
'kty': 'RSA',
'n': long_to_base64(public_key.n),
'e': long_to_base64(public_key.e),
}
if not self.is_public():
data.update({
'd': long_to_base64(self._prepared_key.d),
'p': long_to_base64(self._prepared_key.p),
'q': long_to_base64(self._prepared_key.q),
'dp': long_to_base64(self._prepared_key.exp1),
'dq': long_to_base64(self._prepared_key.exp2),
'qi': long_to_base64(self._prepared_key.coef),
})
return data
|
mpdavis/python-jose | jose/backends/rsa_backend.py | _rsa_recover_prime_factors | python | def _rsa_recover_prime_factors(n, e, d):
# See 8.2.2(i) in Handbook of Applied Cryptography.
ktot = d * e - 1
# The quantity d*e-1 is a multiple of phi(n), even,
# and can be represented as t*2^s.
t = ktot
while t % 2 == 0:
t = t // 2
# Cycle through all multiplicative inverses in Zn.
# The algorithm is non-deterministic, but there is a 50% chance
# any candidate a leads to successful factoring.
# See "Digitalized Signatures and Public Key Functions as Intractable
# as Factorization", M. Rabin, 1979
spotted = False
a = 2
while not spotted and a < _MAX_RECOVERY_ATTEMPTS:
k = t
# Cycle through all values a^{t*2^i}=a^k
while k < ktot:
cand = pow(a, k, n)
# Check if a^k is a non-trivial root of unity (mod n)
if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1:
# We have found a number such that (cand-1)(cand+1)=0 (mod n).
# Either of the terms divides n.
p = _gcd(cand + 1, n)
spotted = True
break
k *= 2
# This value was not any good... let's try another!
a += 2
if not spotted:
raise ValueError("Unable to compute factors p and q from exponent d.")
# Found !
q, r = divmod(n, p)
assert r == 0
p, q = sorted((p, q), reverse=True)
return (p, q) | Compute factors p and q from the private exponent d. We assume that n has
no more than two factors. This function is adapted from code in PyCrypto. | train | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/backends/rsa_backend.py#L54-L94 | null | import binascii
import six
from pyasn1.error import PyAsn1Error
import rsa as pyrsa
import rsa.pem as pyrsa_pem
from jose.backends.base import Key
from jose.backends._asn1 import (
rsa_private_key_pkcs1_to_pkcs8,
rsa_private_key_pkcs8_to_pkcs1,
rsa_public_key_pkcs1_to_pkcs8,
)
from jose.constants import ALGORITHMS
from jose.exceptions import JWKError
from jose.utils import base64_to_long, long_to_base64
LEGACY_INVALID_PKCS8_RSA_HEADER = binascii.unhexlify(
"30" # sequence
"8204BD" # DER-encoded sequence contents length of 1213 bytes -- INCORRECT STATIC LENGTH
"020100" # integer: 0 -- Version
"30" # sequence
"0D" # DER-encoded sequence contents length of 13 bytes -- PrivateKeyAlgorithmIdentifier
"06092A864886F70D010101" # OID -- rsaEncryption
"0500" # NULL -- parameters
)
ASN1_SEQUENCE_ID = binascii.unhexlify("30")
RSA_ENCRYPTION_ASN1_OID = "1.2.840.113549.1.1.1"
# Functions gcd and rsa_recover_prime_factors were copied from cryptography 1.9
# to enable pure python rsa module to be in compliance with section 6.3.1 of RFC7518
# which requires only private exponent (d) for private key.
def _gcd(a, b):
"""Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b:
a, b = b, (a % b)
return a
# Controls the number of iterations rsa_recover_prime_factors will perform
# to obtain the prime factors. Each iteration increments by 2 so the actual
# maximum attempts is half this number.
_MAX_RECOVERY_ATTEMPTS = 1000
def pem_to_spki(pem, fmt='PKCS8'):
key = RSAKey(pem, ALGORITHMS.RS256)
return key.to_pem(fmt)
def _legacy_private_key_pkcs8_to_pkcs1(pkcs8_key):
"""Legacy RSA private key PKCS8-to-PKCS1 conversion.
.. warning::
This is incorrect parsing and only works because the legacy PKCS1-to-PKCS8
encoding was also incorrect.
"""
# Only allow this processing if the prefix matches
# AND the following byte indicates an ASN1 sequence,
# as we would expect with the legacy encoding.
if not pkcs8_key.startswith(LEGACY_INVALID_PKCS8_RSA_HEADER + ASN1_SEQUENCE_ID):
raise ValueError("Invalid private key encoding")
return pkcs8_key[len(LEGACY_INVALID_PKCS8_RSA_HEADER):]
class RSAKey(Key):
SHA256 = 'SHA-256'
SHA384 = 'SHA-384'
SHA512 = 'SHA-512'
def __init__(self, key, algorithm):
if algorithm not in ALGORITHMS.RSA:
raise JWKError('hash_alg: %s is not a valid hash algorithm' % algorithm)
self.hash_alg = {
ALGORITHMS.RS256: self.SHA256,
ALGORITHMS.RS384: self.SHA384,
ALGORITHMS.RS512: self.SHA512
}.get(algorithm)
self._algorithm = algorithm
if isinstance(key, dict):
self._prepared_key = self._process_jwk(key)
return
if isinstance(key, (pyrsa.PublicKey, pyrsa.PrivateKey)):
self._prepared_key = key
return
if isinstance(key, six.string_types):
key = key.encode('utf-8')
if isinstance(key, six.binary_type):
try:
self._prepared_key = pyrsa.PublicKey.load_pkcs1(key)
except ValueError:
try:
self._prepared_key = pyrsa.PublicKey.load_pkcs1_openssl_pem(key)
except ValueError:
try:
self._prepared_key = pyrsa.PrivateKey.load_pkcs1(key)
except ValueError:
try:
der = pyrsa_pem.load_pem(key, b'PRIVATE KEY')
try:
pkcs1_key = rsa_private_key_pkcs8_to_pkcs1(der)
except PyAsn1Error:
# If the key was encoded using the old, invalid,
# encoding then pyasn1 will throw an error attempting
# to parse the key.
pkcs1_key = _legacy_private_key_pkcs8_to_pkcs1(der)
self._prepared_key = pyrsa.PrivateKey.load_pkcs1(pkcs1_key, format="DER")
except ValueError as e:
raise JWKError(e)
return
raise JWKError('Unable to parse an RSA_JWK from key: %s' % key)
def _process_jwk(self, jwk_dict):
if not jwk_dict.get('kty') == 'RSA':
raise JWKError("Incorrect key type. Expected: 'RSA', Recieved: %s" % jwk_dict.get('kty'))
e = base64_to_long(jwk_dict.get('e'))
n = base64_to_long(jwk_dict.get('n'))
if 'd' not in jwk_dict:
return pyrsa.PublicKey(e=e, n=n)
else:
d = base64_to_long(jwk_dict.get('d'))
extra_params = ['p', 'q', 'dp', 'dq', 'qi']
if any(k in jwk_dict for k in extra_params):
# Precomputed private key parameters are available.
if not all(k in jwk_dict for k in extra_params):
# These values must be present when 'p' is according to
# Section 6.3.2 of RFC7518, so if they are not we raise
# an error.
raise JWKError('Precomputed private key parameters are incomplete.')
p = base64_to_long(jwk_dict['p'])
q = base64_to_long(jwk_dict['q'])
return pyrsa.PrivateKey(e=e, n=n, d=d, p=p, q=q)
else:
p, q = _rsa_recover_prime_factors(n, e, d)
return pyrsa.PrivateKey(n=n, e=e, d=d, p=p, q=q)
def sign(self, msg):
return pyrsa.sign(msg, self._prepared_key, self.hash_alg)
def verify(self, msg, sig):
try:
pyrsa.verify(msg, sig, self._prepared_key)
return True
except pyrsa.pkcs1.VerificationError:
return False
def is_public(self):
return isinstance(self._prepared_key, pyrsa.PublicKey)
def public_key(self):
if isinstance(self._prepared_key, pyrsa.PublicKey):
return self
return self.__class__(pyrsa.PublicKey(n=self._prepared_key.n, e=self._prepared_key.e), self._algorithm)
def to_pem(self, pem_format='PKCS8'):
if isinstance(self._prepared_key, pyrsa.PrivateKey):
der = self._prepared_key.save_pkcs1(format='DER')
if pem_format == 'PKCS8':
pkcs8_der = rsa_private_key_pkcs1_to_pkcs8(der)
pem = pyrsa_pem.save_pem(pkcs8_der, pem_marker='PRIVATE KEY')
elif pem_format == 'PKCS1':
pem = pyrsa_pem.save_pem(der, pem_marker='RSA PRIVATE KEY')
else:
raise ValueError("Invalid pem format specified: %r" % (pem_format,))
else:
if pem_format == 'PKCS8':
pkcs1_der = self._prepared_key.save_pkcs1(format="DER")
pkcs8_der = rsa_public_key_pkcs1_to_pkcs8(pkcs1_der)
pem = pyrsa_pem.save_pem(pkcs8_der, pem_marker='PUBLIC KEY')
elif pem_format == 'PKCS1':
der = self._prepared_key.save_pkcs1(format='DER')
pem = pyrsa_pem.save_pem(der, pem_marker='RSA PUBLIC KEY')
else:
raise ValueError("Invalid pem format specified: %r" % (pem_format,))
return pem
def to_dict(self):
if not self.is_public():
public_key = self.public_key()._prepared_key
else:
public_key = self._prepared_key
data = {
'alg': self._algorithm,
'kty': 'RSA',
'n': long_to_base64(public_key.n),
'e': long_to_base64(public_key.e),
}
if not self.is_public():
data.update({
'd': long_to_base64(self._prepared_key.d),
'p': long_to_base64(self._prepared_key.p),
'q': long_to_base64(self._prepared_key.q),
'dp': long_to_base64(self._prepared_key.exp1),
'dq': long_to_base64(self._prepared_key.exp2),
'qi': long_to_base64(self._prepared_key.coef),
})
return data
|
mpdavis/python-jose | jose/backends/rsa_backend.py | _legacy_private_key_pkcs8_to_pkcs1 | python | def _legacy_private_key_pkcs8_to_pkcs1(pkcs8_key):
# Only allow this processing if the prefix matches
# AND the following byte indicates an ASN1 sequence,
# as we would expect with the legacy encoding.
if not pkcs8_key.startswith(LEGACY_INVALID_PKCS8_RSA_HEADER + ASN1_SEQUENCE_ID):
raise ValueError("Invalid private key encoding")
return pkcs8_key[len(LEGACY_INVALID_PKCS8_RSA_HEADER):] | Legacy RSA private key PKCS8-to-PKCS1 conversion.
.. warning::
This is incorrect parsing and only works because the legacy PKCS1-to-PKCS8
encoding was also incorrect. | train | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/backends/rsa_backend.py#L102-L116 | null | import binascii
import six
from pyasn1.error import PyAsn1Error
import rsa as pyrsa
import rsa.pem as pyrsa_pem
from jose.backends.base import Key
from jose.backends._asn1 import (
rsa_private_key_pkcs1_to_pkcs8,
rsa_private_key_pkcs8_to_pkcs1,
rsa_public_key_pkcs1_to_pkcs8,
)
from jose.constants import ALGORITHMS
from jose.exceptions import JWKError
from jose.utils import base64_to_long, long_to_base64
LEGACY_INVALID_PKCS8_RSA_HEADER = binascii.unhexlify(
"30" # sequence
"8204BD" # DER-encoded sequence contents length of 1213 bytes -- INCORRECT STATIC LENGTH
"020100" # integer: 0 -- Version
"30" # sequence
"0D" # DER-encoded sequence contents length of 13 bytes -- PrivateKeyAlgorithmIdentifier
"06092A864886F70D010101" # OID -- rsaEncryption
"0500" # NULL -- parameters
)
ASN1_SEQUENCE_ID = binascii.unhexlify("30")
RSA_ENCRYPTION_ASN1_OID = "1.2.840.113549.1.1.1"
# Functions gcd and rsa_recover_prime_factors were copied from cryptography 1.9
# to enable pure python rsa module to be in compliance with section 6.3.1 of RFC7518
# which requires only private exponent (d) for private key.
def _gcd(a, b):
"""Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b:
a, b = b, (a % b)
return a
# Controls the number of iterations rsa_recover_prime_factors will perform
# to obtain the prime factors. Each iteration increments by 2 so the actual
# maximum attempts is half this number.
_MAX_RECOVERY_ATTEMPTS = 1000
def _rsa_recover_prime_factors(n, e, d):
"""
Compute factors p and q from the private exponent d. We assume that n has
no more than two factors. This function is adapted from code in PyCrypto.
"""
# See 8.2.2(i) in Handbook of Applied Cryptography.
ktot = d * e - 1
# The quantity d*e-1 is a multiple of phi(n), even,
# and can be represented as t*2^s.
t = ktot
while t % 2 == 0:
t = t // 2
# Cycle through all multiplicative inverses in Zn.
# The algorithm is non-deterministic, but there is a 50% chance
# any candidate a leads to successful factoring.
# See "Digitalized Signatures and Public Key Functions as Intractable
# as Factorization", M. Rabin, 1979
spotted = False
a = 2
while not spotted and a < _MAX_RECOVERY_ATTEMPTS:
k = t
# Cycle through all values a^{t*2^i}=a^k
while k < ktot:
cand = pow(a, k, n)
# Check if a^k is a non-trivial root of unity (mod n)
if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1:
# We have found a number such that (cand-1)(cand+1)=0 (mod n).
# Either of the terms divides n.
p = _gcd(cand + 1, n)
spotted = True
break
k *= 2
# This value was not any good... let's try another!
a += 2
if not spotted:
raise ValueError("Unable to compute factors p and q from exponent d.")
# Found !
q, r = divmod(n, p)
assert r == 0
p, q = sorted((p, q), reverse=True)
return (p, q)
def pem_to_spki(pem, fmt='PKCS8'):
key = RSAKey(pem, ALGORITHMS.RS256)
return key.to_pem(fmt)
class RSAKey(Key):
SHA256 = 'SHA-256'
SHA384 = 'SHA-384'
SHA512 = 'SHA-512'
def __init__(self, key, algorithm):
if algorithm not in ALGORITHMS.RSA:
raise JWKError('hash_alg: %s is not a valid hash algorithm' % algorithm)
self.hash_alg = {
ALGORITHMS.RS256: self.SHA256,
ALGORITHMS.RS384: self.SHA384,
ALGORITHMS.RS512: self.SHA512
}.get(algorithm)
self._algorithm = algorithm
if isinstance(key, dict):
self._prepared_key = self._process_jwk(key)
return
if isinstance(key, (pyrsa.PublicKey, pyrsa.PrivateKey)):
self._prepared_key = key
return
if isinstance(key, six.string_types):
key = key.encode('utf-8')
if isinstance(key, six.binary_type):
try:
self._prepared_key = pyrsa.PublicKey.load_pkcs1(key)
except ValueError:
try:
self._prepared_key = pyrsa.PublicKey.load_pkcs1_openssl_pem(key)
except ValueError:
try:
self._prepared_key = pyrsa.PrivateKey.load_pkcs1(key)
except ValueError:
try:
der = pyrsa_pem.load_pem(key, b'PRIVATE KEY')
try:
pkcs1_key = rsa_private_key_pkcs8_to_pkcs1(der)
except PyAsn1Error:
# If the key was encoded using the old, invalid,
# encoding then pyasn1 will throw an error attempting
# to parse the key.
pkcs1_key = _legacy_private_key_pkcs8_to_pkcs1(der)
self._prepared_key = pyrsa.PrivateKey.load_pkcs1(pkcs1_key, format="DER")
except ValueError as e:
raise JWKError(e)
return
raise JWKError('Unable to parse an RSA_JWK from key: %s' % key)
def _process_jwk(self, jwk_dict):
if not jwk_dict.get('kty') == 'RSA':
raise JWKError("Incorrect key type. Expected: 'RSA', Recieved: %s" % jwk_dict.get('kty'))
e = base64_to_long(jwk_dict.get('e'))
n = base64_to_long(jwk_dict.get('n'))
if 'd' not in jwk_dict:
return pyrsa.PublicKey(e=e, n=n)
else:
d = base64_to_long(jwk_dict.get('d'))
extra_params = ['p', 'q', 'dp', 'dq', 'qi']
if any(k in jwk_dict for k in extra_params):
# Precomputed private key parameters are available.
if not all(k in jwk_dict for k in extra_params):
# These values must be present when 'p' is according to
# Section 6.3.2 of RFC7518, so if they are not we raise
# an error.
raise JWKError('Precomputed private key parameters are incomplete.')
p = base64_to_long(jwk_dict['p'])
q = base64_to_long(jwk_dict['q'])
return pyrsa.PrivateKey(e=e, n=n, d=d, p=p, q=q)
else:
p, q = _rsa_recover_prime_factors(n, e, d)
return pyrsa.PrivateKey(n=n, e=e, d=d, p=p, q=q)
def sign(self, msg):
return pyrsa.sign(msg, self._prepared_key, self.hash_alg)
def verify(self, msg, sig):
try:
pyrsa.verify(msg, sig, self._prepared_key)
return True
except pyrsa.pkcs1.VerificationError:
return False
def is_public(self):
return isinstance(self._prepared_key, pyrsa.PublicKey)
def public_key(self):
if isinstance(self._prepared_key, pyrsa.PublicKey):
return self
return self.__class__(pyrsa.PublicKey(n=self._prepared_key.n, e=self._prepared_key.e), self._algorithm)
def to_pem(self, pem_format='PKCS8'):
if isinstance(self._prepared_key, pyrsa.PrivateKey):
der = self._prepared_key.save_pkcs1(format='DER')
if pem_format == 'PKCS8':
pkcs8_der = rsa_private_key_pkcs1_to_pkcs8(der)
pem = pyrsa_pem.save_pem(pkcs8_der, pem_marker='PRIVATE KEY')
elif pem_format == 'PKCS1':
pem = pyrsa_pem.save_pem(der, pem_marker='RSA PRIVATE KEY')
else:
raise ValueError("Invalid pem format specified: %r" % (pem_format,))
else:
if pem_format == 'PKCS8':
pkcs1_der = self._prepared_key.save_pkcs1(format="DER")
pkcs8_der = rsa_public_key_pkcs1_to_pkcs8(pkcs1_der)
pem = pyrsa_pem.save_pem(pkcs8_der, pem_marker='PUBLIC KEY')
elif pem_format == 'PKCS1':
der = self._prepared_key.save_pkcs1(format='DER')
pem = pyrsa_pem.save_pem(der, pem_marker='RSA PUBLIC KEY')
else:
raise ValueError("Invalid pem format specified: %r" % (pem_format,))
return pem
def to_dict(self):
if not self.is_public():
public_key = self.public_key()._prepared_key
else:
public_key = self._prepared_key
data = {
'alg': self._algorithm,
'kty': 'RSA',
'n': long_to_base64(public_key.n),
'e': long_to_base64(public_key.e),
}
if not self.is_public():
data.update({
'd': long_to_base64(self._prepared_key.d),
'p': long_to_base64(self._prepared_key.p),
'q': long_to_base64(self._prepared_key.q),
'dp': long_to_base64(self._prepared_key.exp1),
'dq': long_to_base64(self._prepared_key.exp2),
'qi': long_to_base64(self._prepared_key.coef),
})
return data
|
mpdavis/python-jose | jose/utils.py | calculate_at_hash | python | def calculate_at_hash(access_token, hash_alg):
hash_digest = hash_alg(access_token.encode('utf-8')).digest()
cut_at = int(len(hash_digest) / 2)
truncated = hash_digest[:cut_at]
at_hash = base64url_encode(truncated)
return at_hash.decode('utf-8') | Helper method for calculating an access token
hash, as described in http://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
Its value is the base64url encoding of the left-most half of the hash of the octets
of the ASCII representation of the access_token value, where the hash algorithm
used is the hash algorithm used in the alg Header Parameter of the ID Token's JOSE
Header. For instance, if the alg is RS256, hash the access_token value with SHA-256,
then take the left-most 128 bits and base64url encode them. The at_hash value is a
case sensitive string.
Args:
access_token (str): An access token string.
hash_alg (callable): A callable returning a hash object, e.g. hashlib.sha256 | train | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/utils.py#L55-L75 | [
"def base64url_encode(input):\n \"\"\"Helper method to base64url_encode a string.\n\n Args:\n input (str): A base64url_encoded string to encode.\n\n \"\"\"\n return base64.urlsafe_b64encode(input).replace(b'=', b'')\n"
] |
import base64
import hmac
import six
import struct
import sys
if sys.version_info > (3,):
# Deal with integer compatibilities between Python 2 and 3.
# Using `from builtins import int` is not supported on AppEngine.
long = int
# Piggyback of the backends implementation of the function that converts a long
# to a bytes stream. Some plumbing is necessary to have the signatures match.
try:
from Crypto.Util.number import long_to_bytes
except ImportError:
try:
from cryptography.utils import int_to_bytes as _long_to_bytes
def long_to_bytes(n, blocksize=0):
return _long_to_bytes(n, blocksize or None)
except ImportError:
from ecdsa.ecdsa import int_to_string as _long_to_bytes
def long_to_bytes(n, blocksize=0):
ret = _long_to_bytes(n)
if blocksize == 0:
return ret
else:
assert len(ret) <= blocksize
padding = blocksize - len(ret)
return b'\x00' * padding + ret
def long_to_base64(data, size=0):
return base64.urlsafe_b64encode(long_to_bytes(data, size)).strip(b'=')
def int_arr_to_long(arr):
return long(''.join(["%02x" % byte for byte in arr]), 16)
def base64_to_long(data):
if isinstance(data, six.text_type):
data = data.encode("ascii")
# urlsafe_b64decode will happily convert b64encoded data
_d = base64.urlsafe_b64decode(bytes(data) + b'==')
return int_arr_to_long(struct.unpack('%sB' % len(_d), _d))
def base64url_decode(input):
"""Helper method to base64url_decode a string.
Args:
input (str): A base64url_encoded string to decode.
"""
rem = len(input) % 4
if rem > 0:
input += b'=' * (4 - rem)
return base64.urlsafe_b64decode(input)
def base64url_encode(input):
"""Helper method to base64url_encode a string.
Args:
input (str): A base64url_encoded string to encode.
"""
return base64.urlsafe_b64encode(input).replace(b'=', b'')
def timedelta_total_seconds(delta):
"""Helper method to determine the total number of seconds
from a timedelta.
Args:
delta (timedelta): A timedelta to convert to seconds.
"""
return delta.days * 24 * 60 * 60 + delta.seconds
def constant_time_string_compare(a, b):
"""Helper for comparing string in constant time, independent
of the python version being used.
Args:
a (str): A string to compare
b (str): A string to compare
"""
try:
return hmac.compare_digest(a, b)
except AttributeError:
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0
|
mpdavis/python-jose | jose/utils.py | base64url_decode | python | def base64url_decode(input):
rem = len(input) % 4
if rem > 0:
input += b'=' * (4 - rem)
return base64.urlsafe_b64decode(input) | Helper method to base64url_decode a string.
Args:
input (str): A base64url_encoded string to decode. | train | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/utils.py#L78-L90 | null |
import base64
import hmac
import six
import struct
import sys
if sys.version_info > (3,):
# Deal with integer compatibilities between Python 2 and 3.
# Using `from builtins import int` is not supported on AppEngine.
long = int
# Piggyback of the backends implementation of the function that converts a long
# to a bytes stream. Some plumbing is necessary to have the signatures match.
try:
from Crypto.Util.number import long_to_bytes
except ImportError:
try:
from cryptography.utils import int_to_bytes as _long_to_bytes
def long_to_bytes(n, blocksize=0):
return _long_to_bytes(n, blocksize or None)
except ImportError:
from ecdsa.ecdsa import int_to_string as _long_to_bytes
def long_to_bytes(n, blocksize=0):
ret = _long_to_bytes(n)
if blocksize == 0:
return ret
else:
assert len(ret) <= blocksize
padding = blocksize - len(ret)
return b'\x00' * padding + ret
def long_to_base64(data, size=0):
return base64.urlsafe_b64encode(long_to_bytes(data, size)).strip(b'=')
def int_arr_to_long(arr):
return long(''.join(["%02x" % byte for byte in arr]), 16)
def base64_to_long(data):
if isinstance(data, six.text_type):
data = data.encode("ascii")
# urlsafe_b64decode will happily convert b64encoded data
_d = base64.urlsafe_b64decode(bytes(data) + b'==')
return int_arr_to_long(struct.unpack('%sB' % len(_d), _d))
def calculate_at_hash(access_token, hash_alg):
"""Helper method for calculating an access token
hash, as described in http://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
Its value is the base64url encoding of the left-most half of the hash of the octets
of the ASCII representation of the access_token value, where the hash algorithm
used is the hash algorithm used in the alg Header Parameter of the ID Token's JOSE
Header. For instance, if the alg is RS256, hash the access_token value with SHA-256,
then take the left-most 128 bits and base64url encode them. The at_hash value is a
case sensitive string.
Args:
access_token (str): An access token string.
hash_alg (callable): A callable returning a hash object, e.g. hashlib.sha256
"""
hash_digest = hash_alg(access_token.encode('utf-8')).digest()
cut_at = int(len(hash_digest) / 2)
truncated = hash_digest[:cut_at]
at_hash = base64url_encode(truncated)
return at_hash.decode('utf-8')
def base64url_encode(input):
"""Helper method to base64url_encode a string.
Args:
input (str): A base64url_encoded string to encode.
"""
return base64.urlsafe_b64encode(input).replace(b'=', b'')
def timedelta_total_seconds(delta):
"""Helper method to determine the total number of seconds
from a timedelta.
Args:
delta (timedelta): A timedelta to convert to seconds.
"""
return delta.days * 24 * 60 * 60 + delta.seconds
def constant_time_string_compare(a, b):
"""Helper for comparing string in constant time, independent
of the python version being used.
Args:
a (str): A string to compare
b (str): A string to compare
"""
try:
return hmac.compare_digest(a, b)
except AttributeError:
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0
|
mpdavis/python-jose | jose/utils.py | constant_time_string_compare | python | def constant_time_string_compare(a, b):
try:
return hmac.compare_digest(a, b)
except AttributeError:
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0 | Helper for comparing string in constant time, independent
of the python version being used.
Args:
a (str): A string to compare
b (str): A string to compare | train | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/utils.py#L113-L134 | null |
import base64
import hmac
import six
import struct
import sys
if sys.version_info > (3,):
# Deal with integer compatibilities between Python 2 and 3.
# Using `from builtins import int` is not supported on AppEngine.
long = int
# Piggyback of the backends implementation of the function that converts a long
# to a bytes stream. Some plumbing is necessary to have the signatures match.
try:
from Crypto.Util.number import long_to_bytes
except ImportError:
try:
from cryptography.utils import int_to_bytes as _long_to_bytes
def long_to_bytes(n, blocksize=0):
return _long_to_bytes(n, blocksize or None)
except ImportError:
from ecdsa.ecdsa import int_to_string as _long_to_bytes
def long_to_bytes(n, blocksize=0):
ret = _long_to_bytes(n)
if blocksize == 0:
return ret
else:
assert len(ret) <= blocksize
padding = blocksize - len(ret)
return b'\x00' * padding + ret
def long_to_base64(data, size=0):
return base64.urlsafe_b64encode(long_to_bytes(data, size)).strip(b'=')
def int_arr_to_long(arr):
return long(''.join(["%02x" % byte for byte in arr]), 16)
def base64_to_long(data):
if isinstance(data, six.text_type):
data = data.encode("ascii")
# urlsafe_b64decode will happily convert b64encoded data
_d = base64.urlsafe_b64decode(bytes(data) + b'==')
return int_arr_to_long(struct.unpack('%sB' % len(_d), _d))
def calculate_at_hash(access_token, hash_alg):
"""Helper method for calculating an access token
hash, as described in http://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
Its value is the base64url encoding of the left-most half of the hash of the octets
of the ASCII representation of the access_token value, where the hash algorithm
used is the hash algorithm used in the alg Header Parameter of the ID Token's JOSE
Header. For instance, if the alg is RS256, hash the access_token value with SHA-256,
then take the left-most 128 bits and base64url encode them. The at_hash value is a
case sensitive string.
Args:
access_token (str): An access token string.
hash_alg (callable): A callable returning a hash object, e.g. hashlib.sha256
"""
hash_digest = hash_alg(access_token.encode('utf-8')).digest()
cut_at = int(len(hash_digest) / 2)
truncated = hash_digest[:cut_at]
at_hash = base64url_encode(truncated)
return at_hash.decode('utf-8')
def base64url_decode(input):
"""Helper method to base64url_decode a string.
Args:
input (str): A base64url_encoded string to decode.
"""
rem = len(input) % 4
if rem > 0:
input += b'=' * (4 - rem)
return base64.urlsafe_b64decode(input)
def base64url_encode(input):
"""Helper method to base64url_encode a string.
Args:
input (str): A base64url_encoded string to encode.
"""
return base64.urlsafe_b64encode(input).replace(b'=', b'')
def timedelta_total_seconds(delta):
"""Helper method to determine the total number of seconds
from a timedelta.
Args:
delta (timedelta): A timedelta to convert to seconds.
"""
return delta.days * 24 * 60 * 60 + delta.seconds
|
mpdavis/python-jose | jose/jws.py | sign | python | def sign(payload, key, headers=None, algorithm=ALGORITHMS.HS256):
if algorithm not in ALGORITHMS.SUPPORTED:
raise JWSError('Algorithm %s not supported.' % algorithm)
encoded_header = _encode_header(algorithm, additional_headers=headers)
encoded_payload = _encode_payload(payload)
signed_output = _sign_header_and_claims(encoded_header, encoded_payload, algorithm, key)
return signed_output | Signs a claims set and returns a JWS string.
Args:
payload (str): A string to sign
key (str or dict): The key to use for signing the claim set. Can be
individual JWK or JWK set.
headers (dict, optional): A set of headers that will be added to
the default headers. Any headers that are added as additional
headers will override the default headers.
algorithm (str, optional): The algorithm to use for signing the
the claims. Defaults to HS256.
Returns:
str: The string representation of the header, claims, and signature.
Raises:
JWSError: If there is an error signing the token.
Examples:
>>> jws.sign({'a': 'b'}, 'secret', algorithm='HS256')
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8' | train | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/jws.py#L19-L52 | [
"def _encode_header(algorithm, additional_headers=None):\n header = {\n \"typ\": \"JWT\",\n \"alg\": algorithm\n }\n\n if additional_headers:\n header.update(additional_headers)\n\n json_header = json.dumps(\n header,\n separators=(',', ':'),\n sort_keys=True,\n... |
import binascii
import json
import six
try:
from collections.abc import Mapping, Iterable # Python 3
except ImportError:
from collections import Mapping, Iterable # Python 2, will be deprecated in Python 3.8
from jose import jwk
from jose.constants import ALGORITHMS
from jose.exceptions import JWSError
from jose.exceptions import JWSSignatureError
from jose.utils import base64url_encode
from jose.utils import base64url_decode
def verify(token, key, algorithms, verify=True):
"""Verifies a JWS string's signature.
Args:
token (str): A signed JWS to be verified.
key (str or dict): A key to attempt to verify the payload with. Can be
individual JWK or JWK set.
algorithms (str or list): Valid algorithms that should be used to verify the JWS.
Returns:
str: The str representation of the payload, assuming the signature is valid.
Raises:
JWSError: If there is an exception verifying a token.
Examples:
>>> token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
>>> jws.verify(token, 'secret', algorithms='HS256')
"""
header, payload, signing_input, signature = _load(token)
if verify:
_verify_signature(signing_input, header, signature, key, algorithms)
return payload
def get_unverified_header(token):
"""Returns the decoded headers without verification of any kind.
Args:
token (str): A signed JWS to decode the headers from.
Returns:
dict: The dict representation of the token headers.
Raises:
JWSError: If there is an exception decoding the token.
"""
header, claims, signing_input, signature = _load(token)
return header
def get_unverified_headers(token):
"""Returns the decoded headers without verification of any kind.
This is simply a wrapper of get_unverified_header() for backwards
compatibility.
Args:
token (str): A signed JWS to decode the headers from.
Returns:
dict: The dict representation of the token headers.
Raises:
JWSError: If there is an exception decoding the token.
"""
return get_unverified_header(token)
def get_unverified_claims(token):
"""Returns the decoded claims without verification of any kind.
Args:
token (str): A signed JWS to decode the headers from.
Returns:
str: The str representation of the token claims.
Raises:
JWSError: If there is an exception decoding the token.
"""
header, claims, signing_input, signature = _load(token)
return claims
def _encode_header(algorithm, additional_headers=None):
header = {
"typ": "JWT",
"alg": algorithm
}
if additional_headers:
header.update(additional_headers)
json_header = json.dumps(
header,
separators=(',', ':'),
sort_keys=True,
).encode('utf-8')
return base64url_encode(json_header)
def _encode_payload(payload):
if isinstance(payload, Mapping):
try:
payload = json.dumps(
payload,
separators=(',', ':'),
).encode('utf-8')
except ValueError:
pass
return base64url_encode(payload)
def _sign_header_and_claims(encoded_header, encoded_claims, algorithm, key_data):
signing_input = b'.'.join([encoded_header, encoded_claims])
try:
key = jwk.construct(key_data, algorithm)
signature = key.sign(signing_input)
except Exception as e:
raise JWSError(e)
encoded_signature = base64url_encode(signature)
encoded_string = b'.'.join([encoded_header, encoded_claims, encoded_signature])
return encoded_string.decode('utf-8')
def _load(jwt):
if isinstance(jwt, six.text_type):
jwt = jwt.encode('utf-8')
try:
signing_input, crypto_segment = jwt.rsplit(b'.', 1)
header_segment, claims_segment = signing_input.split(b'.', 1)
header_data = base64url_decode(header_segment)
except ValueError:
raise JWSError('Not enough segments')
except (TypeError, binascii.Error):
raise JWSError('Invalid header padding')
try:
header = json.loads(header_data.decode('utf-8'))
except ValueError as e:
raise JWSError('Invalid header string: %s' % e)
if not isinstance(header, Mapping):
raise JWSError('Invalid header string: must be a json object')
try:
payload = base64url_decode(claims_segment)
except (TypeError, binascii.Error):
raise JWSError('Invalid payload padding')
try:
signature = base64url_decode(crypto_segment)
except (TypeError, binascii.Error):
raise JWSError('Invalid crypto padding')
return (header, payload, signing_input, signature)
def _sig_matches_keys(keys, signing_input, signature, alg):
for key in keys:
key = jwk.construct(key, alg)
try:
if key.verify(signing_input, signature):
return True
except Exception:
pass
return False
def _get_keys(key):
try:
key = json.loads(key)
except Exception:
pass
# JWK Set per RFC 7517
if 'keys' in key:
return key['keys']
# Individual JWK per RFC 7517
elif 'kty' in key:
return (key,)
# Some other mapping. Firebase uses just dict of kid, cert pairs
elif isinstance(key, Mapping):
values = key.values()
if values:
return values
return (key,)
# Iterable but not text or mapping => list- or tuple-like
elif (isinstance(key, Iterable) and
not (isinstance(key, six.string_types) or isinstance(key, Mapping))):
return key
# Scalar value, wrap in tuple.
else:
return (key,)
def _verify_signature(signing_input, header, signature, key='', algorithms=None):
alg = header.get('alg')
if not alg:
raise JWSError('No algorithm was specified in the JWS header.')
if algorithms is not None and alg not in algorithms:
raise JWSError('The specified alg value is not allowed')
keys = _get_keys(key)
try:
if not _sig_matches_keys(keys, signing_input, signature, alg):
raise JWSSignatureError()
except JWSSignatureError:
raise JWSError('Signature verification failed.')
except JWSError:
raise JWSError('Invalid or unsupported algorithm: %s' % alg)
|
mpdavis/python-jose | jose/jws.py | verify | python | def verify(token, key, algorithms, verify=True):
header, payload, signing_input, signature = _load(token)
if verify:
_verify_signature(signing_input, header, signature, key, algorithms)
return payload | Verifies a JWS string's signature.
Args:
token (str): A signed JWS to be verified.
key (str or dict): A key to attempt to verify the payload with. Can be
individual JWK or JWK set.
algorithms (str or list): Valid algorithms that should be used to verify the JWS.
Returns:
str: The str representation of the payload, assuming the signature is valid.
Raises:
JWSError: If there is an exception verifying a token.
Examples:
>>> token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
>>> jws.verify(token, 'secret', algorithms='HS256') | train | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/jws.py#L55-L82 | [
"def _load(jwt):\n if isinstance(jwt, six.text_type):\n jwt = jwt.encode('utf-8')\n try:\n signing_input, crypto_segment = jwt.rsplit(b'.', 1)\n header_segment, claims_segment = signing_input.split(b'.', 1)\n header_data = base64url_decode(header_segment)\n except ValueError:\n ... |
import binascii
import json
import six
try:
from collections.abc import Mapping, Iterable # Python 3
except ImportError:
from collections import Mapping, Iterable # Python 2, will be deprecated in Python 3.8
from jose import jwk
from jose.constants import ALGORITHMS
from jose.exceptions import JWSError
from jose.exceptions import JWSSignatureError
from jose.utils import base64url_encode
from jose.utils import base64url_decode
def sign(payload, key, headers=None, algorithm=ALGORITHMS.HS256):
"""Signs a claims set and returns a JWS string.
Args:
payload (str): A string to sign
key (str or dict): The key to use for signing the claim set. Can be
individual JWK or JWK set.
headers (dict, optional): A set of headers that will be added to
the default headers. Any headers that are added as additional
headers will override the default headers.
algorithm (str, optional): The algorithm to use for signing the
the claims. Defaults to HS256.
Returns:
str: The string representation of the header, claims, and signature.
Raises:
JWSError: If there is an error signing the token.
Examples:
>>> jws.sign({'a': 'b'}, 'secret', algorithm='HS256')
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
"""
if algorithm not in ALGORITHMS.SUPPORTED:
raise JWSError('Algorithm %s not supported.' % algorithm)
encoded_header = _encode_header(algorithm, additional_headers=headers)
encoded_payload = _encode_payload(payload)
signed_output = _sign_header_and_claims(encoded_header, encoded_payload, algorithm, key)
return signed_output
def get_unverified_header(token):
"""Returns the decoded headers without verification of any kind.
Args:
token (str): A signed JWS to decode the headers from.
Returns:
dict: The dict representation of the token headers.
Raises:
JWSError: If there is an exception decoding the token.
"""
header, claims, signing_input, signature = _load(token)
return header
def get_unverified_headers(token):
"""Returns the decoded headers without verification of any kind.
This is simply a wrapper of get_unverified_header() for backwards
compatibility.
Args:
token (str): A signed JWS to decode the headers from.
Returns:
dict: The dict representation of the token headers.
Raises:
JWSError: If there is an exception decoding the token.
"""
return get_unverified_header(token)
def get_unverified_claims(token):
"""Returns the decoded claims without verification of any kind.
Args:
token (str): A signed JWS to decode the headers from.
Returns:
str: The str representation of the token claims.
Raises:
JWSError: If there is an exception decoding the token.
"""
header, claims, signing_input, signature = _load(token)
return claims
def _encode_header(algorithm, additional_headers=None):
header = {
"typ": "JWT",
"alg": algorithm
}
if additional_headers:
header.update(additional_headers)
json_header = json.dumps(
header,
separators=(',', ':'),
sort_keys=True,
).encode('utf-8')
return base64url_encode(json_header)
def _encode_payload(payload):
if isinstance(payload, Mapping):
try:
payload = json.dumps(
payload,
separators=(',', ':'),
).encode('utf-8')
except ValueError:
pass
return base64url_encode(payload)
def _sign_header_and_claims(encoded_header, encoded_claims, algorithm, key_data):
signing_input = b'.'.join([encoded_header, encoded_claims])
try:
key = jwk.construct(key_data, algorithm)
signature = key.sign(signing_input)
except Exception as e:
raise JWSError(e)
encoded_signature = base64url_encode(signature)
encoded_string = b'.'.join([encoded_header, encoded_claims, encoded_signature])
return encoded_string.decode('utf-8')
def _load(jwt):
if isinstance(jwt, six.text_type):
jwt = jwt.encode('utf-8')
try:
signing_input, crypto_segment = jwt.rsplit(b'.', 1)
header_segment, claims_segment = signing_input.split(b'.', 1)
header_data = base64url_decode(header_segment)
except ValueError:
raise JWSError('Not enough segments')
except (TypeError, binascii.Error):
raise JWSError('Invalid header padding')
try:
header = json.loads(header_data.decode('utf-8'))
except ValueError as e:
raise JWSError('Invalid header string: %s' % e)
if not isinstance(header, Mapping):
raise JWSError('Invalid header string: must be a json object')
try:
payload = base64url_decode(claims_segment)
except (TypeError, binascii.Error):
raise JWSError('Invalid payload padding')
try:
signature = base64url_decode(crypto_segment)
except (TypeError, binascii.Error):
raise JWSError('Invalid crypto padding')
return (header, payload, signing_input, signature)
def _sig_matches_keys(keys, signing_input, signature, alg):
for key in keys:
key = jwk.construct(key, alg)
try:
if key.verify(signing_input, signature):
return True
except Exception:
pass
return False
def _get_keys(key):
try:
key = json.loads(key)
except Exception:
pass
# JWK Set per RFC 7517
if 'keys' in key:
return key['keys']
# Individual JWK per RFC 7517
elif 'kty' in key:
return (key,)
# Some other mapping. Firebase uses just dict of kid, cert pairs
elif isinstance(key, Mapping):
values = key.values()
if values:
return values
return (key,)
# Iterable but not text or mapping => list- or tuple-like
elif (isinstance(key, Iterable) and
not (isinstance(key, six.string_types) or isinstance(key, Mapping))):
return key
# Scalar value, wrap in tuple.
else:
return (key,)
def _verify_signature(signing_input, header, signature, key='', algorithms=None):
alg = header.get('alg')
if not alg:
raise JWSError('No algorithm was specified in the JWS header.')
if algorithms is not None and alg not in algorithms:
raise JWSError('The specified alg value is not allowed')
keys = _get_keys(key)
try:
if not _sig_matches_keys(keys, signing_input, signature, alg):
raise JWSSignatureError()
except JWSSignatureError:
raise JWSError('Signature verification failed.')
except JWSError:
raise JWSError('Invalid or unsupported algorithm: %s' % alg)
|
mpdavis/python-jose | jose/jwk.py | construct | python | def construct(key_data, algorithm=None):
# Allow for pulling the algorithm off of the passed in jwk.
if not algorithm and isinstance(key_data, dict):
algorithm = key_data.get('alg', None)
if not algorithm:
raise JWKError('Unable to find a algorithm for key: %s' % key_data)
key_class = get_key(algorithm)
if not key_class:
raise JWKError('Unable to find a algorithm for key: %s' % key_data)
return key_class(key_data, algorithm) | Construct a Key object for the given algorithm with the given
key_data. | train | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/jwk.py#L45-L61 | [
"def get_key(algorithm):\n if algorithm in ALGORITHMS.KEYS:\n return ALGORITHMS.KEYS[algorithm]\n elif algorithm in ALGORITHMS.HMAC:\n return HMACKey\n elif algorithm in ALGORITHMS.RSA:\n from jose.backends import RSAKey # noqa: F811\n return RSAKey\n elif algorithm in ALGOR... |
import hashlib
import hmac
import six
from jose.constants import ALGORITHMS
from jose.exceptions import JWKError
from jose.utils import base64url_decode, base64url_encode
from jose.utils import constant_time_string_compare
from jose.backends.base import Key
try:
from jose.backends import RSAKey # noqa: F401
except ImportError:
pass
try:
from jose.backends import ECKey # noqa: F401
except ImportError:
pass
def get_key(algorithm):
if algorithm in ALGORITHMS.KEYS:
return ALGORITHMS.KEYS[algorithm]
elif algorithm in ALGORITHMS.HMAC:
return HMACKey
elif algorithm in ALGORITHMS.RSA:
from jose.backends import RSAKey # noqa: F811
return RSAKey
elif algorithm in ALGORITHMS.EC:
from jose.backends import ECKey # noqa: F811
return ECKey
return None
def register_key(algorithm, key_class):
if not issubclass(key_class, Key):
raise TypeError("Key class not a subclass of jwk.Key")
ALGORITHMS.KEYS[algorithm] = key_class
ALGORITHMS.SUPPORTED.add(algorithm)
return True
def get_algorithm_object(algorithm):
algorithms = {
ALGORITHMS.HS256: 'SHA256',
ALGORITHMS.HS384: 'SHA384',
ALGORITHMS.HS512: 'SHA512',
ALGORITHMS.RS256: 'SHA256',
ALGORITHMS.RS384: 'SHA384',
ALGORITHMS.RS512: 'SHA512',
ALGORITHMS.ES256: 'SHA256',
ALGORITHMS.ES384: 'SHA384',
ALGORITHMS.ES512: 'SHA512',
}
key = get_key(algorithm)
attr = algorithms.get(algorithm, None)
return getattr(key, attr)
class HMACKey(Key):
"""
Performs signing and verification operations using HMAC
and the specified hash function.
"""
SHA256 = hashlib.sha256
SHA384 = hashlib.sha384
SHA512 = hashlib.sha512
def __init__(self, key, algorithm):
if algorithm not in ALGORITHMS.HMAC:
raise JWKError('hash_alg: %s is not a valid hash algorithm' % algorithm)
self._algorithm = algorithm
self.hash_alg = get_algorithm_object(algorithm)
if isinstance(key, dict):
self.prepared_key = self._process_jwk(key)
return
if not isinstance(key, six.string_types) and not isinstance(key, bytes):
raise JWKError('Expecting a string- or bytes-formatted key.')
if isinstance(key, six.text_type):
key = key.encode('utf-8')
invalid_strings = [
b'-----BEGIN PUBLIC KEY-----',
b'-----BEGIN RSA PUBLIC KEY-----',
b'-----BEGIN CERTIFICATE-----',
b'ssh-rsa'
]
if any(string_value in key for string_value in invalid_strings):
raise JWKError(
'The specified key is an asymmetric key or x509 certificate and'
' should not be used as an HMAC secret.')
self.prepared_key = key
def _process_jwk(self, jwk_dict):
if not jwk_dict.get('kty') == 'oct':
raise JWKError("Incorrect key type. Expected: 'oct', Recieved: %s" % jwk_dict.get('kty'))
k = jwk_dict.get('k')
k = k.encode('utf-8')
k = bytes(k)
k = base64url_decode(k)
return k
def sign(self, msg):
return hmac.new(self.prepared_key, msg, self.hash_alg).digest()
def verify(self, msg, sig):
return constant_time_string_compare(sig, self.sign(msg))
def to_dict(self):
return {
'alg': self._algorithm,
'kty': 'oct',
'k': base64url_encode(self.prepared_key),
}
|
slimkrazy/python-google-places | googleplaces/__init__.py | _fetch_remote_json | python | def _fetch_remote_json(service_url, params=None, use_http_post=False):
if not params:
params = {}
request_url, response = _fetch_remote(service_url, params, use_http_post)
if six.PY3:
str_response = response.read().decode('utf-8')
return (request_url, json.loads(str_response, parse_float=Decimal))
return (request_url, json.load(response, parse_float=Decimal)) | Retrieves a JSON object from a URL. | train | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L73-L82 | [
"def _fetch_remote(service_url, params=None, use_http_post=False):\n if not params:\n params = {}\n\n encoded_data = {}\n for k, v in params.items():\n if isinstance(v, six.string_types):\n v = v.encode('utf-8')\n encoded_data[k] = v\n encoded_data = urllib.parse.urlencod... | """
A simple wrapper around the 'experimental' Google Places API, documented
here: http://code.google.com/apis/maps/documentation/places/. This library
also makes use of the v3 Maps API for geocoding.
Prerequisites: A Google API key with Places activated against it. Please
check the Google API console, here: http://code.google.com/apis/console
NOTE: Please ensure that you read the Google terms of service (labelled 'Limits
and Requirements' on the documentation url) prior to using this library in a
production environment.
@author: sam@slimkrazy.com
"""
from __future__ import absolute_import
import cgi
from decimal import Decimal
try:
import json
except ImportError:
import simplejson as json
try:
import six
from six.moves import urllib
except ImportError:
pass
import warnings
from . import lang
from . import ranking
__all__ = ['GooglePlaces', 'GooglePlacesError', 'GooglePlacesAttributeError',
'geocode_location']
__version__ = '1.4.1'
__author__ = 'Samuel Adu'
__email__ = 'sam@slimkrazy.com'
class cached_property(object):
def __init__(self, func):
self.func = func
def __get__(self, instance, cls=None):
result = instance.__dict__[self.func.__name__] = self.func(instance)
return result
def _fetch_remote(service_url, params=None, use_http_post=False):
if not params:
params = {}
encoded_data = {}
for k, v in params.items():
if isinstance(v, six.string_types):
v = v.encode('utf-8')
encoded_data[k] = v
encoded_data = urllib.parse.urlencode(encoded_data)
if not use_http_post:
query_url = (service_url if service_url.endswith('?') else
'%s?' % service_url)
request_url = query_url + encoded_data
request = urllib.request.Request(request_url)
else:
request_url = service_url
request = urllib.request.Request(service_url, data=encoded_data)
return (request_url, urllib.request.urlopen(request))
def _fetch_remote_file(service_url, params=None, use_http_post=False):
"""Retrieves a file from a URL.
Returns a tuple (mimetype, filename, data)
"""
if not params:
params = {}
request_url, response = _fetch_remote(service_url, params, use_http_post)
dummy, params = cgi.parse_header(
response.headers.get('Content-Disposition', ''))
fn = params['filename']
return (response.headers.get('content-type'),
fn, response.read(), response.geturl())
def geocode_location(location, sensor=False, api_key=None):
"""Converts a human-readable location to lat-lng.
Returns a dict with lat and lng keys.
keyword arguments:
location -- A human-readable location, e.g 'London, England'
sensor -- Boolean flag denoting if the location came from a device using
its' location sensor (default False)
api_key -- A valid Google Places API key.
raises:
GooglePlacesError -- if the geocoder fails to find a location.
"""
params = {'address': location, 'sensor': str(sensor).lower()}
if api_key is not None:
params['key'] = api_key
url, geo_response = _fetch_remote_json(
GooglePlaces.GEOCODE_API_URL, params)
_validate_response(url, geo_response)
if geo_response['status'] == GooglePlaces.RESPONSE_STATUS_ZERO_RESULTS:
error_detail = ('Lat/Lng for location \'%s\' can\'t be determined.' %
location)
raise GooglePlacesError(error_detail)
return geo_response['results'][0]['geometry']['location']
def _get_place_details(place_id, api_key, sensor=False,
language=lang.ENGLISH):
"""Gets a detailed place response.
keyword arguments:
place_id -- The unique identifier for the required place.
"""
url, detail_response = _fetch_remote_json(GooglePlaces.DETAIL_API_URL,
{'placeid': place_id,
'sensor': str(sensor).lower(),
'key': api_key,
'language': language})
_validate_response(url, detail_response)
return detail_response['result']
def _get_place_photo(photoreference, api_key, maxheight=None, maxwidth=None,
sensor=False):
"""Gets a place's photo by reference.
See detailed documentation at https://developers.google.com/places/documentation/photos
Arguments:
photoreference -- The unique Google reference for the required photo.
Keyword arguments:
maxheight -- The maximum desired photo height in pixels
maxwidth -- The maximum desired photo width in pixels
You must specify one of this keyword arguments. Acceptable value is an
integer between 1 and 1600.
"""
params = {'photoreference': photoreference,
'sensor': str(sensor).lower(),
'key': api_key}
if maxheight:
params['maxheight'] = maxheight
if maxwidth:
params['maxwidth'] = maxwidth
return _fetch_remote_file(GooglePlaces.PHOTO_API_URL, params)
def _validate_response(url, response):
"""Validates that the response from Google was successful."""
if response['status'] not in [GooglePlaces.RESPONSE_STATUS_OK,
GooglePlaces.RESPONSE_STATUS_ZERO_RESULTS]:
error_detail = ('Request to URL %s failed with response code: %s' %
(url, response['status']))
raise GooglePlacesError(error_detail)
class GooglePlacesError(Exception):
pass
class GooglePlacesAttributeError(AttributeError):
"""Exception thrown when a detailed property is unavailable.
A search query from the places API returns only a summary of the Place.
in order to get full details, a further API call must be made using
the place_id. This exception will be thrown when a property made
available by only the detailed API call is looked up against the summary
object.
An explicit call to get_details() must be made on the summary object in
order to convert a summary object to a detailed object.
"""
# I could spend forever muling between this design decision and creating
# a PlaceSummary object as well as a Place object. I'm leaning towards this
# method in order to keep the API as simple as possible.
pass
class GooglePlaces(object):
"""A wrapper around the Google Places Query API."""
BASE_URL = 'https://maps.googleapis.com/maps/api'
PLACE_URL = BASE_URL + '/place'
GEOCODE_API_URL = BASE_URL + '/geocode/json?'
RADAR_SEARCH_API_URL = PLACE_URL + '/radarsearch/json?'
NEARBY_SEARCH_API_URL = PLACE_URL + '/nearbysearch/json?'
TEXT_SEARCH_API_URL = PLACE_URL + '/textsearch/json?'
AUTOCOMPLETE_API_URL = PLACE_URL + '/autocomplete/json?'
DETAIL_API_URL = PLACE_URL + '/details/json?'
CHECKIN_API_URL = PLACE_URL + '/check-in/json?sensor=%s&key=%s'
ADD_API_URL = PLACE_URL + '/add/json?sensor=%s&key=%s'
DELETE_API_URL = PLACE_URL + '/delete/json?sensor=%s&key=%s'
PHOTO_API_URL = PLACE_URL + '/photo?'
MAXIMUM_SEARCH_RADIUS = 50000
RESPONSE_STATUS_OK = 'OK'
RESPONSE_STATUS_ZERO_RESULTS = 'ZERO_RESULTS'
def __init__(self, api_key):
self._api_key = api_key
self._sensor = False
self._request_params = None
def query(self, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter('always')
warnings.warn('The query API is deprecated. Please use nearby_search.',
DeprecationWarning, stacklevel=2)
return self.nearby_search(**kwargs)
def nearby_search(self, language=lang.ENGLISH, keyword=None, location=None,
lat_lng=None, name=None, radius=3200, rankby=ranking.PROMINENCE,
sensor=False, type=None, types=[], pagetoken=None):
"""Perform a nearby search using the Google Places API.
One of either location, lat_lng or pagetoken are required, the rest of
the keyword arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
location -- A human readable location, e.g 'London, England'
(default None)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
name -- A term to be matched against the names of the Places.
Results will be restricted to those containing the passed
name value. (default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
rankby -- Specifies the order in which results are listed :
ranking.PROMINENCE (default) or ranking.DISTANCE
(imply no radius argument).
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
"""
if location is None and lat_lng is None and pagetoken is None:
raise ValueError('One of location, lat_lng or pagetoken must be passed in.')
if rankby == 'distance':
# As per API docs rankby == distance:
# One or more of keyword, name, or types is required.
if keyword is None and types == [] and name is None:
raise ValueError('When rankby = googleplaces.ranking.DISTANCE, ' +
'name, keyword or types kwargs ' +
'must be specified.')
self._sensor = sensor
radius = (radius if radius <= GooglePlaces.MAXIMUM_SEARCH_RADIUS
else GooglePlaces.MAXIMUM_SEARCH_RADIUS)
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params = {'location': lat_lng_str}
if rankby == 'prominence':
self._request_params['radius'] = radius
else:
self._request_params['rankby'] = rankby
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.NEARBY_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def text_search(self, query=None, language=lang.ENGLISH, lat_lng=None,
radius=3200, type=None, types=[], location=None, pagetoken=None):
"""Perform a text search using the Google Places API.
Only the one of the query or pagetoken kwargs are required, the rest of the
keyword arguments are optional.
keyword arguments:
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
query -- The text string on which to search, for example:
"Restaurant in New York".
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
"""
self._request_params = {'query': query}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.TEXT_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def autocomplete(self, input, lat_lng=None, location=None, radius=3200,
language=lang.ENGLISH, types=None, components=[]):
"""
Perform an autocomplete search using the Google Places API.
Only the input kwarg is required, the rest of the keyword arguments
are optional.
keyword arguments:
input -- The text string on which to search, for example:
"Hattie B's".
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location to which the
search is to be restricted. The maximum is 50000 meters.
(default 3200)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
types -- A type to search against. See `types.py` "autocomplete types"
for complete list
https://developers.google.com/places/documentation/autocomplete#place_types.
components -- An optional grouping of places to which you would
like to restrict your results. An array containing one or
more tuples of:
* country: matches a country name or a two letter ISO 3166-1 country code.
eg: [('country','US')]
"""
self._request_params = {'input': input}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if types:
self._request_params['types'] = types
if len(components) > 0:
self._request_params['components'] = '|'.join(['{}:{}'.format(
c[0],c[1]) for c in components])
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.AUTOCOMPLETE_API_URL, self._request_params)
_validate_response(url, places_response)
return GoogleAutocompleteSearchResult(self, places_response)
def radar_search(self, sensor=False, keyword=None, name=None,
language=lang.ENGLISH, lat_lng=None, opennow=False,
radius=3200, type=None, types=[], location=None):
"""Perform a radar search using the Google Places API.
One of lat_lng or location are required, the rest of the keyword
arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
name -- A term to be matched against the names of Places. Results will
be restricted to those containing the passed name value.
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
opennow -- Returns only those Places that are open for business at the time
the query is sent. (default False)
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param
"""
if keyword is None and name is None and len(types) is 0:
raise ValueError('One of keyword, name or types must be supplied.')
if location is None and lat_lng is None:
raise ValueError('One of location or lat_lng must be passed in.')
try:
radius = int(radius)
except:
raise ValueError('radius must be passed supplied as an integer.')
if sensor not in [True, False]:
raise ValueError('sensor must be passed in as a boolean value.')
self._request_params = {'radius': radius}
self._sensor = sensor
self._request_params['location'] = self._generate_lat_lng_string(
lat_lng, location)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if opennow is True:
self._request_params['opennow'] = 'true'
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.RADAR_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def checkin(self, place_id, sensor=False):
"""Checks in a user to a place.
keyword arguments:
place_id -- The unique Google identifier for the relevant place.
sensor -- Boolean flag denoting if the location came from a
device using its location sensor (default False).
"""
data = {'placeid': place_id}
url, checkin_response = _fetch_remote_json(
GooglePlaces.CHECKIN_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(data), use_http_post=True)
_validate_response(url, checkin_response)
def get_place(self, place_id, sensor=False, language=lang.ENGLISH):
"""Gets a detailed place object.
keyword arguments:
place_id -- The unique Google identifier for the required place.
sensor -- Boolean flag denoting if the location came from a
device using its' location sensor (default False).
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
"""
place_details = _get_place_details(place_id,
self.api_key, sensor, language=language)
return Place(self, place_details)
def add_place(self, **kwargs):
"""Adds a place to the Google Places database.
On a successful request, this method will return a dict containing
the the new Place's place_id and id in keys 'place_id' and 'id'
respectively.
keyword arguments:
name -- The full text name of the Place. Limited to 255
characters.
lat_lng -- A dict containing the following keys: lat, lng.
accuracy -- The accuracy of the location signal on which this request
is based, expressed in meters.
types -- The category in which this Place belongs. Only one type
can currently be specified for a Place. A string or
single element list may be passed in.
language -- The language in which the Place's name is being reported.
(defaults 'en').
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
required_kwargs = {'name': [str], 'lat_lng': [dict],
'accuracy': [int], 'types': [str, list]}
request_params = {}
for key in required_kwargs:
if key not in kwargs or kwargs[key] is None:
raise ValueError('The %s argument is required.' % key)
expected_types = required_kwargs[key]
type_is_valid = False
for expected_type in expected_types:
if isinstance(kwargs[key], expected_type):
type_is_valid = True
break
if not type_is_valid:
raise ValueError('Invalid value for %s' % key)
if key is not 'lat_lng':
request_params[key] = kwargs[key]
if len(kwargs['name']) > 255:
raise ValueError('The place name must not exceed 255 characters ' +
'in length.')
try:
kwargs['lat_lng']['lat']
kwargs['lat_lng']['lng']
request_params['location'] = kwargs['lat_lng']
except KeyError:
raise ValueError('Invalid keys for lat_lng.')
request_params['language'] = (kwargs.get('language')
if kwargs.get('language') is not None else
lang.ENGLISH)
sensor = (kwargs.get('sensor')
if kwargs.get('sensor') is not None else
False)
# At some point Google might support multiple types, so this supports
# strings and lists.
if isinstance(kwargs['types'], str):
request_params['types'] = [kwargs['types']]
else:
request_params['types'] = kwargs['types']
url, add_response = _fetch_remote_json(
GooglePlaces.ADD_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, add_response)
return {'place_id': add_response['place_id'],
'id': add_response['id']}
def delete_place(self, place_id, sensor=False):
"""Deletes a place from the Google Places database.
keyword arguments:
place_id -- The textual identifier that uniquely identifies this
Place, returned from a Place Search request.
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
request_params = {'place_id': place_id}
url, delete_response = _fetch_remote_json(
GooglePlaces.DELETE_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, delete_response)
def _add_required_param_keys(self):
self._request_params['key'] = self.api_key
self._request_params['sensor'] = str(self.sensor).lower()
def _generate_lat_lng_string(self, lat_lng, location):
try:
return '%(lat)s,%(lng)s' % (lat_lng if lat_lng is not None
else geocode_location(location=location, api_key=self.api_key))
except GooglePlacesError as e:
raise ValueError(
'lat_lng must be a dict with the keys, \'lat\' and \'lng\'. Cause: %s' % str(e))
@property
def request_params(self):
return self._request_params
@property
def api_key(self):
return self._api_key
@property
def sensor(self):
return self._sensor
class GoogleAutocompleteSearchResult(object):
"""Wrapper around the Google Autocomplete API query JSON response."""
def __init__(self, query_instance, response):
self._response = response
self._predictions = []
for prediction in response['predictions']:
self._predictions.append(Prediction(query_instance, prediction))
@property
def raw_response(self):
"""Returns the raw JSON response returned by the Autocomplete API."""
return self._response
@property
def predictions(self):
return self._predictions
def __repr__(self):
"""Return a string representation stating number of predictions."""
return '<{} with {} prediction(s)>'.format(
self.__class__.__name__,
len(self.predictions)
)
class Prediction(object):
"""
Represents a prediction from the results of a Google Places Autocomplete API query.
"""
def __init__(self, query_instance, prediction):
self._query_instance = query_instance
self._description = prediction['description']
self._id = prediction['id']
self._matched_substrings = prediction['matched_substrings']
self._place_id = prediction['place_id']
self._reference = prediction['reference']
self._terms = prediction['terms']
self._types = prediction.get('types',[])
if prediction.get('_description') is None:
self._place = None
else:
self._place = prediction
@property
def description(self):
"""
String representation of a Prediction location. Generally contains
name, country, and elements contained in the terms property.
"""
return self._description
@property
def id(self):
"""
Returns the deprecated id property.
This identifier may not be used to retrieve information about this
place, but is guaranteed to be valid across sessions. It can be used
to consolidate data about this Place, and to verify the identity of a
Place across separate searches.
This property is deprecated:
https://developers.google.com/places/documentation/autocomplete#deprecation
"""
return self._id
@property
def matched_substrings(self):
"""
Returns the placement and offset of the matched strings for this search.
A an array of dicts, each with the keys 'length' and 'offset', will be returned.
"""
return self._matched_substrings
@property
def place_id(self):
"""
Returns the unique stable identifier denoting this place.
This identifier may be used to retrieve information about this
place.
This should be considered the primary identifier of a place.
"""
return self._place_id
@property
def reference(self):
"""
Returns the deprecated reference property.
The token can be used to retrieve additional information about this
place when invoking the getPlace method on an GooglePlaces instance.
You can store this token and use it at any time in future to refresh
cached data about this Place, but the same token is not guaranteed to
be returned for any given Place across different searches.
This property is deprecated:
https://developers.google.com/places/documentation/autocomplete#deprecation
"""
return self._reference
@property
def terms(self):
"""
A list of terms which build up the description string
A an array of dicts, each with the keys `offset` and `value`, will be returned.
"""
return self._terms
@property
def types(self):
"""
Returns a list of feature types describing the given result.
"""
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types
# The following properties require a further API call in order to be
# available.
@property
def place(self):
"""
Returns the JSON response from Google Places Detail search API.
"""
self._validate_status()
return self._place
def get_details(self, language=None):
"""
Retrieves full information on the place matching the place_id.
Stores the response in the `place` property.
"""
if self._place is None:
if language is None:
try:
language = self._query_instance._request_params['language']
except KeyError:
language = lang.ENGLISH
place = _get_place_details(
self.place_id, self._query_instance.api_key,
self._query_instance.sensor, language=language)
self._place = Place(self._query_instance, place)
def _validate_status(self):
"""
Indicates specific properties are only available after a details call.
"""
if self._place is None:
error_detail = ('The attribute requested is only available after ' +
'an explicit call to get_details() is made.')
raise GooglePlacesAttributeError(error_detail)
def __repr__(self):
""" Return a string representation with description. """
return '<{} description="{}">'.format(self.__class__.__name__, self.description)
class GooglePlacesSearchResult(object):
"""
Wrapper around the Google Places API query JSON response.
"""
def __init__(self, query_instance, response):
self._response = response
self._places = []
for place in response['results']:
self._places.append(Place(query_instance, place))
self._html_attributions = response.get('html_attributions', [])
self._next_page_token = response.get('next_page_token', [])
@property
def raw_response(self):
"""
Returns the raw JSON response returned by the Places API.
"""
return self._response
@property
def places(self):
return self._places
@property
def html_attributions(self):
"""Returns the HTML attributions for the specified response.
Any returned HTML attributions MUST be displayed as-is, in accordance
with the requirements as found in the documentation. Please see the
module comments for links to the relevant url.
"""
return self._html_attributions
@property
def next_page_token(self):
"""Returns the next page token(next_page_token)."""
return self._next_page_token
@property
def has_attributions(self):
"""Returns a flag denoting if the response had any html attributions."""
return len(self.html_attributions) > 0
@property
def has_next_page_token(self):
"""Returns a flag denoting if the response had a next page token."""
return len(self.next_page_token) > 0
def __repr__(self):
""" Return a string representation stating the number of results."""
return '<{} with {} result(s)>'.format(self.__class__.__name__, len(self.places))
class Place(object):
"""
Represents a place from the results of a Google Places API query.
"""
def __init__(self, query_instance, place_data):
self._query_instance = query_instance
self._place_id = place_data['place_id']
self._id = place_data.get('id', '')
self._reference = place_data.get('reference', '')
self._name = place_data.get('name','')
self._vicinity = place_data.get('vicinity', '')
self._geo_location = place_data['geometry']['location']
self._rating = place_data.get('rating','')
self._types = place_data.get('types','')
self._icon = place_data.get('icon','')
if place_data.get('address_components') is None:
self._details = None
else:
self._details = place_data
@property
def reference(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns contains a unique token for the place.
The token can be used to retrieve additional information about this
place when invoking the getPlace method on an GooglePlaces instance.
You can store this token and use it at any time in future to refresh
cached data about this Place, but the same token is not guaranteed to
be returned for any given Place across different searches."""
warnings.warn('The "reference" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._reference
@property
def id(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns the unique stable identifier denoting this place.
This identifier may not be used to retrieve information about this
place, but is guaranteed to be valid across sessions. It can be used
to consolidate data about this Place, and to verify the identity of a
Place across separate searches.
"""
warnings.warn('The "id" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._id
@property
def place_id(self):
"""Returns the unique stable identifier denoting this place.
This identifier may be used to retrieve information about this
place.
This should be considered the primary identifier of a place.
"""
return self._place_id
@property
def icon(self):
"""Returns the URL of a recommended icon for display."""
if self._icon == '' and self.details != None and 'icon' in self.details:
self._icon = self.details['icon']
return self._icon
@property
def types(self):
"""Returns a list of feature types describing the given result."""
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types
@property
def geo_location(self):
"""Returns the lat lng co-ordinates of the place.
A dict with the keys 'lat' and 'lng' will be returned.
"""
return self._geo_location
@property
def name(self):
"""Returns the human-readable name of the place."""
if self._name == '' and self.details != None and 'name' in self.details:
self._name = self.details['name']
return self._name
@property
def vicinity(self):
"""Returns a feature name of a nearby location.
Often this feature refers to a street or neighborhood within the given
results.
"""
if self._vicinity == '' and self.details != None and 'vicinity' in self.details:
self._vicinity = self.details['vicinity']
return self._vicinity
@property
def rating(self):
"""Returns the Place's rating, from 0.0 to 5.0, based on user reviews.
This method will return None for places that have no rating.
"""
if self._rating == '' and self.details != None and 'rating' in self.details:
self._rating = self.details['rating']
return self._rating
# The following properties require a further API call in order to be
# available.
@property
def details(self):
"""Returns the JSON response from Google Places Detail search API."""
self._validate_status()
return self._details
@property
def formatted_address(self):
"""Returns a string containing the human-readable address of this place.
Often this address is equivalent to the "postal address," which
sometimes differs from country to country. (Note that some countries,
such as the United Kingdom, do not allow distribution of complete postal
addresses due to licensing restrictions.)
"""
self._validate_status()
return self.details.get('formatted_address')
@property
def local_phone_number(self):
"""Returns the Place's phone number in its local format."""
self._validate_status()
return self.details.get('formatted_phone_number')
@property
def international_phone_number(self):
self._validate_status()
return self.details.get('international_phone_number')
@property
def website(self):
"""Returns the authoritative website for this Place."""
self._validate_status()
return self.details.get('website')
@property
def url(self):
"""Contains the official Google Place Page URL of this establishment.
Applications must link to or embed the Google Place page on any screen
that shows detailed results about this Place to the user.
"""
self._validate_status()
return self.details.get('url')
@property
def html_attributions(self):
"""Returns the HTML attributions for the specified response.
Any returned HTML attributions MUST be displayed as-is, in accordance
with the requirements as found in the documentation. Please see the
module comments for links to the relevant url.
"""
self._validate_status()
return self.details.get('html_attributions', [])
@property
def has_attributions(self):
"""Returns a flag denoting if the response had any html attributions."""
return (False if self._details is None else
len(self.html_attributions) > 0)
def checkin(self):
"""Checks in an anonymous user in."""
self._query_instance.checkin(self.place_id,
self._query_instance.sensor)
def get_details(self, language=None):
"""Retrieves full information on the place matching the place_id.
Further attributes will be made available on the instance once this
method has been invoked.
keyword arguments:
language -- The language code, indicating in which language the
results should be returned, if possible. This value defaults
to the language that was used to generate the
GooglePlacesSearchResult instance.
"""
if self._details is None:
if language is None:
try:
language = self._query_instance._request_params['language']
except KeyError:
language = lang.ENGLISH
self._details = _get_place_details(
self.place_id, self._query_instance.api_key,
self._query_instance.sensor, language=language)
@cached_property
def photos(self):
self.get_details()
return [Photo(self._query_instance, i)
for i in self.details.get('photos', [])]
def _validate_status(self):
if self._details is None:
error_detail = ('The attribute requested is only available after ' +
'an explicit call to get_details() is made.')
raise GooglePlacesAttributeError(error_detail)
def __repr__(self):
""" Return a string representation including the name, lat, and lng. """
return '<{} name="{}", lat={}, lng={}>'.format(
self.__class__.__name__,
self.name,
self.geo_location['lat'],
self.geo_location['lng']
)
class Photo(object):
def __init__(self, query_instance, attrs):
self._query_instance = query_instance
self.orig_height = attrs.get('height')
self.orig_width = attrs.get('width')
self.html_attributions = attrs.get('html_attributions')
self.photo_reference = attrs.get('photo_reference')
def get(self, maxheight=None, maxwidth=None, sensor=False):
"""Fetch photo from API."""
if not maxheight and not maxwidth:
raise GooglePlacesError('You must specify maxheight or maxwidth!')
result = _get_place_photo(self.photo_reference,
self._query_instance.api_key,
maxheight=maxheight, maxwidth=maxwidth,
sensor=sensor)
self.mimetype, self.filename, self.data, self.url = result
|
slimkrazy/python-google-places | googleplaces/__init__.py | _fetch_remote_file | python | def _fetch_remote_file(service_url, params=None, use_http_post=False):
if not params:
params = {}
request_url, response = _fetch_remote(service_url, params, use_http_post)
dummy, params = cgi.parse_header(
response.headers.get('Content-Disposition', ''))
fn = params['filename']
return (response.headers.get('content-type'),
fn, response.read(), response.geturl()) | Retrieves a file from a URL.
Returns a tuple (mimetype, filename, data) | train | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L84-L98 | null | """
A simple wrapper around the 'experimental' Google Places API, documented
here: http://code.google.com/apis/maps/documentation/places/. This library
also makes use of the v3 Maps API for geocoding.
Prerequisites: A Google API key with Places activated against it. Please
check the Google API console, here: http://code.google.com/apis/console
NOTE: Please ensure that you read the Google terms of service (labelled 'Limits
and Requirements' on the documentation url) prior to using this library in a
production environment.
@author: sam@slimkrazy.com
"""
from __future__ import absolute_import
import cgi
from decimal import Decimal
try:
import json
except ImportError:
import simplejson as json
try:
import six
from six.moves import urllib
except ImportError:
pass
import warnings
from . import lang
from . import ranking
__all__ = ['GooglePlaces', 'GooglePlacesError', 'GooglePlacesAttributeError',
'geocode_location']
__version__ = '1.4.1'
__author__ = 'Samuel Adu'
__email__ = 'sam@slimkrazy.com'
class cached_property(object):
def __init__(self, func):
self.func = func
def __get__(self, instance, cls=None):
result = instance.__dict__[self.func.__name__] = self.func(instance)
return result
def _fetch_remote(service_url, params=None, use_http_post=False):
if not params:
params = {}
encoded_data = {}
for k, v in params.items():
if isinstance(v, six.string_types):
v = v.encode('utf-8')
encoded_data[k] = v
encoded_data = urllib.parse.urlencode(encoded_data)
if not use_http_post:
query_url = (service_url if service_url.endswith('?') else
'%s?' % service_url)
request_url = query_url + encoded_data
request = urllib.request.Request(request_url)
else:
request_url = service_url
request = urllib.request.Request(service_url, data=encoded_data)
return (request_url, urllib.request.urlopen(request))
def _fetch_remote_json(service_url, params=None, use_http_post=False):
"""Retrieves a JSON object from a URL."""
if not params:
params = {}
request_url, response = _fetch_remote(service_url, params, use_http_post)
if six.PY3:
str_response = response.read().decode('utf-8')
return (request_url, json.loads(str_response, parse_float=Decimal))
return (request_url, json.load(response, parse_float=Decimal))
def geocode_location(location, sensor=False, api_key=None):
"""Converts a human-readable location to lat-lng.
Returns a dict with lat and lng keys.
keyword arguments:
location -- A human-readable location, e.g 'London, England'
sensor -- Boolean flag denoting if the location came from a device using
its' location sensor (default False)
api_key -- A valid Google Places API key.
raises:
GooglePlacesError -- if the geocoder fails to find a location.
"""
params = {'address': location, 'sensor': str(sensor).lower()}
if api_key is not None:
params['key'] = api_key
url, geo_response = _fetch_remote_json(
GooglePlaces.GEOCODE_API_URL, params)
_validate_response(url, geo_response)
if geo_response['status'] == GooglePlaces.RESPONSE_STATUS_ZERO_RESULTS:
error_detail = ('Lat/Lng for location \'%s\' can\'t be determined.' %
location)
raise GooglePlacesError(error_detail)
return geo_response['results'][0]['geometry']['location']
def _get_place_details(place_id, api_key, sensor=False,
language=lang.ENGLISH):
"""Gets a detailed place response.
keyword arguments:
place_id -- The unique identifier for the required place.
"""
url, detail_response = _fetch_remote_json(GooglePlaces.DETAIL_API_URL,
{'placeid': place_id,
'sensor': str(sensor).lower(),
'key': api_key,
'language': language})
_validate_response(url, detail_response)
return detail_response['result']
def _get_place_photo(photoreference, api_key, maxheight=None, maxwidth=None,
sensor=False):
"""Gets a place's photo by reference.
See detailed documentation at https://developers.google.com/places/documentation/photos
Arguments:
photoreference -- The unique Google reference for the required photo.
Keyword arguments:
maxheight -- The maximum desired photo height in pixels
maxwidth -- The maximum desired photo width in pixels
You must specify one of this keyword arguments. Acceptable value is an
integer between 1 and 1600.
"""
params = {'photoreference': photoreference,
'sensor': str(sensor).lower(),
'key': api_key}
if maxheight:
params['maxheight'] = maxheight
if maxwidth:
params['maxwidth'] = maxwidth
return _fetch_remote_file(GooglePlaces.PHOTO_API_URL, params)
def _validate_response(url, response):
"""Validates that the response from Google was successful."""
if response['status'] not in [GooglePlaces.RESPONSE_STATUS_OK,
GooglePlaces.RESPONSE_STATUS_ZERO_RESULTS]:
error_detail = ('Request to URL %s failed with response code: %s' %
(url, response['status']))
raise GooglePlacesError(error_detail)
class GooglePlacesError(Exception):
pass
class GooglePlacesAttributeError(AttributeError):
"""Exception thrown when a detailed property is unavailable.
A search query from the places API returns only a summary of the Place.
in order to get full details, a further API call must be made using
the place_id. This exception will be thrown when a property made
available by only the detailed API call is looked up against the summary
object.
An explicit call to get_details() must be made on the summary object in
order to convert a summary object to a detailed object.
"""
# I could spend forever muling between this design decision and creating
# a PlaceSummary object as well as a Place object. I'm leaning towards this
# method in order to keep the API as simple as possible.
pass
class GooglePlaces(object):
"""A wrapper around the Google Places Query API."""
BASE_URL = 'https://maps.googleapis.com/maps/api'
PLACE_URL = BASE_URL + '/place'
GEOCODE_API_URL = BASE_URL + '/geocode/json?'
RADAR_SEARCH_API_URL = PLACE_URL + '/radarsearch/json?'
NEARBY_SEARCH_API_URL = PLACE_URL + '/nearbysearch/json?'
TEXT_SEARCH_API_URL = PLACE_URL + '/textsearch/json?'
AUTOCOMPLETE_API_URL = PLACE_URL + '/autocomplete/json?'
DETAIL_API_URL = PLACE_URL + '/details/json?'
CHECKIN_API_URL = PLACE_URL + '/check-in/json?sensor=%s&key=%s'
ADD_API_URL = PLACE_URL + '/add/json?sensor=%s&key=%s'
DELETE_API_URL = PLACE_URL + '/delete/json?sensor=%s&key=%s'
PHOTO_API_URL = PLACE_URL + '/photo?'
MAXIMUM_SEARCH_RADIUS = 50000
RESPONSE_STATUS_OK = 'OK'
RESPONSE_STATUS_ZERO_RESULTS = 'ZERO_RESULTS'
def __init__(self, api_key):
self._api_key = api_key
self._sensor = False
self._request_params = None
def query(self, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter('always')
warnings.warn('The query API is deprecated. Please use nearby_search.',
DeprecationWarning, stacklevel=2)
return self.nearby_search(**kwargs)
def nearby_search(self, language=lang.ENGLISH, keyword=None, location=None,
lat_lng=None, name=None, radius=3200, rankby=ranking.PROMINENCE,
sensor=False, type=None, types=[], pagetoken=None):
"""Perform a nearby search using the Google Places API.
One of either location, lat_lng or pagetoken are required, the rest of
the keyword arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
location -- A human readable location, e.g 'London, England'
(default None)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
name -- A term to be matched against the names of the Places.
Results will be restricted to those containing the passed
name value. (default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
rankby -- Specifies the order in which results are listed :
ranking.PROMINENCE (default) or ranking.DISTANCE
(imply no radius argument).
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
"""
if location is None and lat_lng is None and pagetoken is None:
raise ValueError('One of location, lat_lng or pagetoken must be passed in.')
if rankby == 'distance':
# As per API docs rankby == distance:
# One or more of keyword, name, or types is required.
if keyword is None and types == [] and name is None:
raise ValueError('When rankby = googleplaces.ranking.DISTANCE, ' +
'name, keyword or types kwargs ' +
'must be specified.')
self._sensor = sensor
radius = (radius if radius <= GooglePlaces.MAXIMUM_SEARCH_RADIUS
else GooglePlaces.MAXIMUM_SEARCH_RADIUS)
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params = {'location': lat_lng_str}
if rankby == 'prominence':
self._request_params['radius'] = radius
else:
self._request_params['rankby'] = rankby
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.NEARBY_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def text_search(self, query=None, language=lang.ENGLISH, lat_lng=None,
radius=3200, type=None, types=[], location=None, pagetoken=None):
"""Perform a text search using the Google Places API.
Only the one of the query or pagetoken kwargs are required, the rest of the
keyword arguments are optional.
keyword arguments:
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
query -- The text string on which to search, for example:
"Restaurant in New York".
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
"""
self._request_params = {'query': query}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.TEXT_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def autocomplete(self, input, lat_lng=None, location=None, radius=3200,
language=lang.ENGLISH, types=None, components=[]):
"""
Perform an autocomplete search using the Google Places API.
Only the input kwarg is required, the rest of the keyword arguments
are optional.
keyword arguments:
input -- The text string on which to search, for example:
"Hattie B's".
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location to which the
search is to be restricted. The maximum is 50000 meters.
(default 3200)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
types -- A type to search against. See `types.py` "autocomplete types"
for complete list
https://developers.google.com/places/documentation/autocomplete#place_types.
components -- An optional grouping of places to which you would
like to restrict your results. An array containing one or
more tuples of:
* country: matches a country name or a two letter ISO 3166-1 country code.
eg: [('country','US')]
"""
self._request_params = {'input': input}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if types:
self._request_params['types'] = types
if len(components) > 0:
self._request_params['components'] = '|'.join(['{}:{}'.format(
c[0],c[1]) for c in components])
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.AUTOCOMPLETE_API_URL, self._request_params)
_validate_response(url, places_response)
return GoogleAutocompleteSearchResult(self, places_response)
def radar_search(self, sensor=False, keyword=None, name=None,
language=lang.ENGLISH, lat_lng=None, opennow=False,
radius=3200, type=None, types=[], location=None):
"""Perform a radar search using the Google Places API.
One of lat_lng or location are required, the rest of the keyword
arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
name -- A term to be matched against the names of Places. Results will
be restricted to those containing the passed name value.
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
opennow -- Returns only those Places that are open for business at the time
the query is sent. (default False)
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param
"""
if keyword is None and name is None and len(types) is 0:
raise ValueError('One of keyword, name or types must be supplied.')
if location is None and lat_lng is None:
raise ValueError('One of location or lat_lng must be passed in.')
try:
radius = int(radius)
except:
raise ValueError('radius must be passed supplied as an integer.')
if sensor not in [True, False]:
raise ValueError('sensor must be passed in as a boolean value.')
self._request_params = {'radius': radius}
self._sensor = sensor
self._request_params['location'] = self._generate_lat_lng_string(
lat_lng, location)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if opennow is True:
self._request_params['opennow'] = 'true'
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.RADAR_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def checkin(self, place_id, sensor=False):
"""Checks in a user to a place.
keyword arguments:
place_id -- The unique Google identifier for the relevant place.
sensor -- Boolean flag denoting if the location came from a
device using its location sensor (default False).
"""
data = {'placeid': place_id}
url, checkin_response = _fetch_remote_json(
GooglePlaces.CHECKIN_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(data), use_http_post=True)
_validate_response(url, checkin_response)
def get_place(self, place_id, sensor=False, language=lang.ENGLISH):
"""Gets a detailed place object.
keyword arguments:
place_id -- The unique Google identifier for the required place.
sensor -- Boolean flag denoting if the location came from a
device using its' location sensor (default False).
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
"""
place_details = _get_place_details(place_id,
self.api_key, sensor, language=language)
return Place(self, place_details)
def add_place(self, **kwargs):
"""Adds a place to the Google Places database.
On a successful request, this method will return a dict containing
the the new Place's place_id and id in keys 'place_id' and 'id'
respectively.
keyword arguments:
name -- The full text name of the Place. Limited to 255
characters.
lat_lng -- A dict containing the following keys: lat, lng.
accuracy -- The accuracy of the location signal on which this request
is based, expressed in meters.
types -- The category in which this Place belongs. Only one type
can currently be specified for a Place. A string or
single element list may be passed in.
language -- The language in which the Place's name is being reported.
(defaults 'en').
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
required_kwargs = {'name': [str], 'lat_lng': [dict],
'accuracy': [int], 'types': [str, list]}
request_params = {}
for key in required_kwargs:
if key not in kwargs or kwargs[key] is None:
raise ValueError('The %s argument is required.' % key)
expected_types = required_kwargs[key]
type_is_valid = False
for expected_type in expected_types:
if isinstance(kwargs[key], expected_type):
type_is_valid = True
break
if not type_is_valid:
raise ValueError('Invalid value for %s' % key)
if key is not 'lat_lng':
request_params[key] = kwargs[key]
if len(kwargs['name']) > 255:
raise ValueError('The place name must not exceed 255 characters ' +
'in length.')
try:
kwargs['lat_lng']['lat']
kwargs['lat_lng']['lng']
request_params['location'] = kwargs['lat_lng']
except KeyError:
raise ValueError('Invalid keys for lat_lng.')
request_params['language'] = (kwargs.get('language')
if kwargs.get('language') is not None else
lang.ENGLISH)
sensor = (kwargs.get('sensor')
if kwargs.get('sensor') is not None else
False)
# At some point Google might support multiple types, so this supports
# strings and lists.
if isinstance(kwargs['types'], str):
request_params['types'] = [kwargs['types']]
else:
request_params['types'] = kwargs['types']
url, add_response = _fetch_remote_json(
GooglePlaces.ADD_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, add_response)
return {'place_id': add_response['place_id'],
'id': add_response['id']}
def delete_place(self, place_id, sensor=False):
"""Deletes a place from the Google Places database.
keyword arguments:
place_id -- The textual identifier that uniquely identifies this
Place, returned from a Place Search request.
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
request_params = {'place_id': place_id}
url, delete_response = _fetch_remote_json(
GooglePlaces.DELETE_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, delete_response)
def _add_required_param_keys(self):
self._request_params['key'] = self.api_key
self._request_params['sensor'] = str(self.sensor).lower()
def _generate_lat_lng_string(self, lat_lng, location):
try:
return '%(lat)s,%(lng)s' % (lat_lng if lat_lng is not None
else geocode_location(location=location, api_key=self.api_key))
except GooglePlacesError as e:
raise ValueError(
'lat_lng must be a dict with the keys, \'lat\' and \'lng\'. Cause: %s' % str(e))
@property
def request_params(self):
return self._request_params
@property
def api_key(self):
return self._api_key
@property
def sensor(self):
return self._sensor
class GoogleAutocompleteSearchResult(object):
"""Wrapper around the Google Autocomplete API query JSON response."""
def __init__(self, query_instance, response):
self._response = response
self._predictions = []
for prediction in response['predictions']:
self._predictions.append(Prediction(query_instance, prediction))
@property
def raw_response(self):
"""Returns the raw JSON response returned by the Autocomplete API."""
return self._response
@property
def predictions(self):
return self._predictions
def __repr__(self):
"""Return a string representation stating number of predictions."""
return '<{} with {} prediction(s)>'.format(
self.__class__.__name__,
len(self.predictions)
)
class Prediction(object):
"""
Represents a prediction from the results of a Google Places Autocomplete API query.
"""
def __init__(self, query_instance, prediction):
self._query_instance = query_instance
self._description = prediction['description']
self._id = prediction['id']
self._matched_substrings = prediction['matched_substrings']
self._place_id = prediction['place_id']
self._reference = prediction['reference']
self._terms = prediction['terms']
self._types = prediction.get('types',[])
if prediction.get('_description') is None:
self._place = None
else:
self._place = prediction
@property
def description(self):
"""
String representation of a Prediction location. Generally contains
name, country, and elements contained in the terms property.
"""
return self._description
@property
def id(self):
"""
Returns the deprecated id property.
This identifier may not be used to retrieve information about this
place, but is guaranteed to be valid across sessions. It can be used
to consolidate data about this Place, and to verify the identity of a
Place across separate searches.
This property is deprecated:
https://developers.google.com/places/documentation/autocomplete#deprecation
"""
return self._id
@property
def matched_substrings(self):
"""
Returns the placement and offset of the matched strings for this search.
A an array of dicts, each with the keys 'length' and 'offset', will be returned.
"""
return self._matched_substrings
@property
def place_id(self):
"""
Returns the unique stable identifier denoting this place.
This identifier may be used to retrieve information about this
place.
This should be considered the primary identifier of a place.
"""
return self._place_id
@property
def reference(self):
"""
Returns the deprecated reference property.
The token can be used to retrieve additional information about this
place when invoking the getPlace method on an GooglePlaces instance.
You can store this token and use it at any time in future to refresh
cached data about this Place, but the same token is not guaranteed to
be returned for any given Place across different searches.
This property is deprecated:
https://developers.google.com/places/documentation/autocomplete#deprecation
"""
return self._reference
@property
def terms(self):
"""
A list of terms which build up the description string
A an array of dicts, each with the keys `offset` and `value`, will be returned.
"""
return self._terms
@property
def types(self):
"""
Returns a list of feature types describing the given result.
"""
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types
# The following properties require a further API call in order to be
# available.
@property
def place(self):
"""
Returns the JSON response from Google Places Detail search API.
"""
self._validate_status()
return self._place
def get_details(self, language=None):
"""
Retrieves full information on the place matching the place_id.
Stores the response in the `place` property.
"""
if self._place is None:
if language is None:
try:
language = self._query_instance._request_params['language']
except KeyError:
language = lang.ENGLISH
place = _get_place_details(
self.place_id, self._query_instance.api_key,
self._query_instance.sensor, language=language)
self._place = Place(self._query_instance, place)
def _validate_status(self):
"""
Indicates specific properties are only available after a details call.
"""
if self._place is None:
error_detail = ('The attribute requested is only available after ' +
'an explicit call to get_details() is made.')
raise GooglePlacesAttributeError(error_detail)
def __repr__(self):
""" Return a string representation with description. """
return '<{} description="{}">'.format(self.__class__.__name__, self.description)
class GooglePlacesSearchResult(object):
"""
Wrapper around the Google Places API query JSON response.
"""
def __init__(self, query_instance, response):
self._response = response
self._places = []
for place in response['results']:
self._places.append(Place(query_instance, place))
self._html_attributions = response.get('html_attributions', [])
self._next_page_token = response.get('next_page_token', [])
@property
def raw_response(self):
"""
Returns the raw JSON response returned by the Places API.
"""
return self._response
@property
def places(self):
return self._places
@property
def html_attributions(self):
"""Returns the HTML attributions for the specified response.
Any returned HTML attributions MUST be displayed as-is, in accordance
with the requirements as found in the documentation. Please see the
module comments for links to the relevant url.
"""
return self._html_attributions
@property
def next_page_token(self):
"""Returns the next page token(next_page_token)."""
return self._next_page_token
@property
def has_attributions(self):
"""Returns a flag denoting if the response had any html attributions."""
return len(self.html_attributions) > 0
@property
def has_next_page_token(self):
"""Returns a flag denoting if the response had a next page token."""
return len(self.next_page_token) > 0
def __repr__(self):
""" Return a string representation stating the number of results."""
return '<{} with {} result(s)>'.format(self.__class__.__name__, len(self.places))
class Place(object):
"""
Represents a place from the results of a Google Places API query.
"""
def __init__(self, query_instance, place_data):
self._query_instance = query_instance
self._place_id = place_data['place_id']
self._id = place_data.get('id', '')
self._reference = place_data.get('reference', '')
self._name = place_data.get('name','')
self._vicinity = place_data.get('vicinity', '')
self._geo_location = place_data['geometry']['location']
self._rating = place_data.get('rating','')
self._types = place_data.get('types','')
self._icon = place_data.get('icon','')
if place_data.get('address_components') is None:
self._details = None
else:
self._details = place_data
@property
def reference(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns contains a unique token for the place.
The token can be used to retrieve additional information about this
place when invoking the getPlace method on an GooglePlaces instance.
You can store this token and use it at any time in future to refresh
cached data about this Place, but the same token is not guaranteed to
be returned for any given Place across different searches."""
warnings.warn('The "reference" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._reference
@property
def id(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns the unique stable identifier denoting this place.
This identifier may not be used to retrieve information about this
place, but is guaranteed to be valid across sessions. It can be used
to consolidate data about this Place, and to verify the identity of a
Place across separate searches.
"""
warnings.warn('The "id" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._id
@property
def place_id(self):
"""Returns the unique stable identifier denoting this place.
This identifier may be used to retrieve information about this
place.
This should be considered the primary identifier of a place.
"""
return self._place_id
@property
def icon(self):
"""Returns the URL of a recommended icon for display."""
if self._icon == '' and self.details != None and 'icon' in self.details:
self._icon = self.details['icon']
return self._icon
@property
def types(self):
"""Returns a list of feature types describing the given result."""
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types
@property
def geo_location(self):
"""Returns the lat lng co-ordinates of the place.
A dict with the keys 'lat' and 'lng' will be returned.
"""
return self._geo_location
@property
def name(self):
"""Returns the human-readable name of the place."""
if self._name == '' and self.details != None and 'name' in self.details:
self._name = self.details['name']
return self._name
@property
def vicinity(self):
"""Returns a feature name of a nearby location.
Often this feature refers to a street or neighborhood within the given
results.
"""
if self._vicinity == '' and self.details != None and 'vicinity' in self.details:
self._vicinity = self.details['vicinity']
return self._vicinity
@property
def rating(self):
"""Returns the Place's rating, from 0.0 to 5.0, based on user reviews.
This method will return None for places that have no rating.
"""
if self._rating == '' and self.details != None and 'rating' in self.details:
self._rating = self.details['rating']
return self._rating
# The following properties require a further API call in order to be
# available.
@property
def details(self):
"""Returns the JSON response from Google Places Detail search API."""
self._validate_status()
return self._details
@property
def formatted_address(self):
"""Returns a string containing the human-readable address of this place.
Often this address is equivalent to the "postal address," which
sometimes differs from country to country. (Note that some countries,
such as the United Kingdom, do not allow distribution of complete postal
addresses due to licensing restrictions.)
"""
self._validate_status()
return self.details.get('formatted_address')
@property
def local_phone_number(self):
"""Returns the Place's phone number in its local format."""
self._validate_status()
return self.details.get('formatted_phone_number')
@property
def international_phone_number(self):
self._validate_status()
return self.details.get('international_phone_number')
@property
def website(self):
"""Returns the authoritative website for this Place."""
self._validate_status()
return self.details.get('website')
@property
def url(self):
"""Contains the official Google Place Page URL of this establishment.
Applications must link to or embed the Google Place page on any screen
that shows detailed results about this Place to the user.
"""
self._validate_status()
return self.details.get('url')
@property
def html_attributions(self):
"""Returns the HTML attributions for the specified response.
Any returned HTML attributions MUST be displayed as-is, in accordance
with the requirements as found in the documentation. Please see the
module comments for links to the relevant url.
"""
self._validate_status()
return self.details.get('html_attributions', [])
@property
def has_attributions(self):
"""Returns a flag denoting if the response had any html attributions."""
return (False if self._details is None else
len(self.html_attributions) > 0)
def checkin(self):
"""Checks in an anonymous user in."""
self._query_instance.checkin(self.place_id,
self._query_instance.sensor)
def get_details(self, language=None):
"""Retrieves full information on the place matching the place_id.
Further attributes will be made available on the instance once this
method has been invoked.
keyword arguments:
language -- The language code, indicating in which language the
results should be returned, if possible. This value defaults
to the language that was used to generate the
GooglePlacesSearchResult instance.
"""
if self._details is None:
if language is None:
try:
language = self._query_instance._request_params['language']
except KeyError:
language = lang.ENGLISH
self._details = _get_place_details(
self.place_id, self._query_instance.api_key,
self._query_instance.sensor, language=language)
@cached_property
def photos(self):
self.get_details()
return [Photo(self._query_instance, i)
for i in self.details.get('photos', [])]
def _validate_status(self):
if self._details is None:
error_detail = ('The attribute requested is only available after ' +
'an explicit call to get_details() is made.')
raise GooglePlacesAttributeError(error_detail)
def __repr__(self):
""" Return a string representation including the name, lat, and lng. """
return '<{} name="{}", lat={}, lng={}>'.format(
self.__class__.__name__,
self.name,
self.geo_location['lat'],
self.geo_location['lng']
)
class Photo(object):
def __init__(self, query_instance, attrs):
self._query_instance = query_instance
self.orig_height = attrs.get('height')
self.orig_width = attrs.get('width')
self.html_attributions = attrs.get('html_attributions')
self.photo_reference = attrs.get('photo_reference')
def get(self, maxheight=None, maxwidth=None, sensor=False):
"""Fetch photo from API."""
if not maxheight and not maxwidth:
raise GooglePlacesError('You must specify maxheight or maxwidth!')
result = _get_place_photo(self.photo_reference,
self._query_instance.api_key,
maxheight=maxheight, maxwidth=maxwidth,
sensor=sensor)
self.mimetype, self.filename, self.data, self.url = result
|
slimkrazy/python-google-places | googleplaces/__init__.py | geocode_location | python | def geocode_location(location, sensor=False, api_key=None):
params = {'address': location, 'sensor': str(sensor).lower()}
if api_key is not None:
params['key'] = api_key
url, geo_response = _fetch_remote_json(
GooglePlaces.GEOCODE_API_URL, params)
_validate_response(url, geo_response)
if geo_response['status'] == GooglePlaces.RESPONSE_STATUS_ZERO_RESULTS:
error_detail = ('Lat/Lng for location \'%s\' can\'t be determined.' %
location)
raise GooglePlacesError(error_detail)
return geo_response['results'][0]['geometry']['location'] | Converts a human-readable location to lat-lng.
Returns a dict with lat and lng keys.
keyword arguments:
location -- A human-readable location, e.g 'London, England'
sensor -- Boolean flag denoting if the location came from a device using
its' location sensor (default False)
api_key -- A valid Google Places API key.
raises:
GooglePlacesError -- if the geocoder fails to find a location. | train | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L100-L124 | [
"def _fetch_remote_json(service_url, params=None, use_http_post=False):\n \"\"\"Retrieves a JSON object from a URL.\"\"\"\n if not params:\n params = {}\n\n request_url, response = _fetch_remote(service_url, params, use_http_post)\n if six.PY3:\n str_response = response.read().decode('utf-... | """
A simple wrapper around the 'experimental' Google Places API, documented
here: http://code.google.com/apis/maps/documentation/places/. This library
also makes use of the v3 Maps API for geocoding.
Prerequisites: A Google API key with Places activated against it. Please
check the Google API console, here: http://code.google.com/apis/console
NOTE: Please ensure that you read the Google terms of service (labelled 'Limits
and Requirements' on the documentation url) prior to using this library in a
production environment.
@author: sam@slimkrazy.com
"""
from __future__ import absolute_import
import cgi
from decimal import Decimal
try:
import json
except ImportError:
import simplejson as json
try:
import six
from six.moves import urllib
except ImportError:
pass
import warnings
from . import lang
from . import ranking
__all__ = ['GooglePlaces', 'GooglePlacesError', 'GooglePlacesAttributeError',
'geocode_location']
__version__ = '1.4.1'
__author__ = 'Samuel Adu'
__email__ = 'sam@slimkrazy.com'
class cached_property(object):
def __init__(self, func):
self.func = func
def __get__(self, instance, cls=None):
result = instance.__dict__[self.func.__name__] = self.func(instance)
return result
def _fetch_remote(service_url, params=None, use_http_post=False):
if not params:
params = {}
encoded_data = {}
for k, v in params.items():
if isinstance(v, six.string_types):
v = v.encode('utf-8')
encoded_data[k] = v
encoded_data = urllib.parse.urlencode(encoded_data)
if not use_http_post:
query_url = (service_url if service_url.endswith('?') else
'%s?' % service_url)
request_url = query_url + encoded_data
request = urllib.request.Request(request_url)
else:
request_url = service_url
request = urllib.request.Request(service_url, data=encoded_data)
return (request_url, urllib.request.urlopen(request))
def _fetch_remote_json(service_url, params=None, use_http_post=False):
"""Retrieves a JSON object from a URL."""
if not params:
params = {}
request_url, response = _fetch_remote(service_url, params, use_http_post)
if six.PY3:
str_response = response.read().decode('utf-8')
return (request_url, json.loads(str_response, parse_float=Decimal))
return (request_url, json.load(response, parse_float=Decimal))
def _fetch_remote_file(service_url, params=None, use_http_post=False):
"""Retrieves a file from a URL.
Returns a tuple (mimetype, filename, data)
"""
if not params:
params = {}
request_url, response = _fetch_remote(service_url, params, use_http_post)
dummy, params = cgi.parse_header(
response.headers.get('Content-Disposition', ''))
fn = params['filename']
return (response.headers.get('content-type'),
fn, response.read(), response.geturl())
def _get_place_details(place_id, api_key, sensor=False,
language=lang.ENGLISH):
"""Gets a detailed place response.
keyword arguments:
place_id -- The unique identifier for the required place.
"""
url, detail_response = _fetch_remote_json(GooglePlaces.DETAIL_API_URL,
{'placeid': place_id,
'sensor': str(sensor).lower(),
'key': api_key,
'language': language})
_validate_response(url, detail_response)
return detail_response['result']
def _get_place_photo(photoreference, api_key, maxheight=None, maxwidth=None,
sensor=False):
"""Gets a place's photo by reference.
See detailed documentation at https://developers.google.com/places/documentation/photos
Arguments:
photoreference -- The unique Google reference for the required photo.
Keyword arguments:
maxheight -- The maximum desired photo height in pixels
maxwidth -- The maximum desired photo width in pixels
You must specify one of this keyword arguments. Acceptable value is an
integer between 1 and 1600.
"""
params = {'photoreference': photoreference,
'sensor': str(sensor).lower(),
'key': api_key}
if maxheight:
params['maxheight'] = maxheight
if maxwidth:
params['maxwidth'] = maxwidth
return _fetch_remote_file(GooglePlaces.PHOTO_API_URL, params)
def _validate_response(url, response):
"""Validates that the response from Google was successful."""
if response['status'] not in [GooglePlaces.RESPONSE_STATUS_OK,
GooglePlaces.RESPONSE_STATUS_ZERO_RESULTS]:
error_detail = ('Request to URL %s failed with response code: %s' %
(url, response['status']))
raise GooglePlacesError(error_detail)
class GooglePlacesError(Exception):
pass
class GooglePlacesAttributeError(AttributeError):
"""Exception thrown when a detailed property is unavailable.
A search query from the places API returns only a summary of the Place.
in order to get full details, a further API call must be made using
the place_id. This exception will be thrown when a property made
available by only the detailed API call is looked up against the summary
object.
An explicit call to get_details() must be made on the summary object in
order to convert a summary object to a detailed object.
"""
# I could spend forever muling between this design decision and creating
# a PlaceSummary object as well as a Place object. I'm leaning towards this
# method in order to keep the API as simple as possible.
pass
class GooglePlaces(object):
"""A wrapper around the Google Places Query API."""
BASE_URL = 'https://maps.googleapis.com/maps/api'
PLACE_URL = BASE_URL + '/place'
GEOCODE_API_URL = BASE_URL + '/geocode/json?'
RADAR_SEARCH_API_URL = PLACE_URL + '/radarsearch/json?'
NEARBY_SEARCH_API_URL = PLACE_URL + '/nearbysearch/json?'
TEXT_SEARCH_API_URL = PLACE_URL + '/textsearch/json?'
AUTOCOMPLETE_API_URL = PLACE_URL + '/autocomplete/json?'
DETAIL_API_URL = PLACE_URL + '/details/json?'
CHECKIN_API_URL = PLACE_URL + '/check-in/json?sensor=%s&key=%s'
ADD_API_URL = PLACE_URL + '/add/json?sensor=%s&key=%s'
DELETE_API_URL = PLACE_URL + '/delete/json?sensor=%s&key=%s'
PHOTO_API_URL = PLACE_URL + '/photo?'
MAXIMUM_SEARCH_RADIUS = 50000
RESPONSE_STATUS_OK = 'OK'
RESPONSE_STATUS_ZERO_RESULTS = 'ZERO_RESULTS'
def __init__(self, api_key):
self._api_key = api_key
self._sensor = False
self._request_params = None
def query(self, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter('always')
warnings.warn('The query API is deprecated. Please use nearby_search.',
DeprecationWarning, stacklevel=2)
return self.nearby_search(**kwargs)
def nearby_search(self, language=lang.ENGLISH, keyword=None, location=None,
lat_lng=None, name=None, radius=3200, rankby=ranking.PROMINENCE,
sensor=False, type=None, types=[], pagetoken=None):
"""Perform a nearby search using the Google Places API.
One of either location, lat_lng or pagetoken are required, the rest of
the keyword arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
location -- A human readable location, e.g 'London, England'
(default None)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
name -- A term to be matched against the names of the Places.
Results will be restricted to those containing the passed
name value. (default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
rankby -- Specifies the order in which results are listed :
ranking.PROMINENCE (default) or ranking.DISTANCE
(imply no radius argument).
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
"""
if location is None and lat_lng is None and pagetoken is None:
raise ValueError('One of location, lat_lng or pagetoken must be passed in.')
if rankby == 'distance':
# As per API docs rankby == distance:
# One or more of keyword, name, or types is required.
if keyword is None and types == [] and name is None:
raise ValueError('When rankby = googleplaces.ranking.DISTANCE, ' +
'name, keyword or types kwargs ' +
'must be specified.')
self._sensor = sensor
radius = (radius if radius <= GooglePlaces.MAXIMUM_SEARCH_RADIUS
else GooglePlaces.MAXIMUM_SEARCH_RADIUS)
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params = {'location': lat_lng_str}
if rankby == 'prominence':
self._request_params['radius'] = radius
else:
self._request_params['rankby'] = rankby
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.NEARBY_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def text_search(self, query=None, language=lang.ENGLISH, lat_lng=None,
radius=3200, type=None, types=[], location=None, pagetoken=None):
"""Perform a text search using the Google Places API.
Only the one of the query or pagetoken kwargs are required, the rest of the
keyword arguments are optional.
keyword arguments:
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
query -- The text string on which to search, for example:
"Restaurant in New York".
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
"""
self._request_params = {'query': query}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.TEXT_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def autocomplete(self, input, lat_lng=None, location=None, radius=3200,
language=lang.ENGLISH, types=None, components=[]):
"""
Perform an autocomplete search using the Google Places API.
Only the input kwarg is required, the rest of the keyword arguments
are optional.
keyword arguments:
input -- The text string on which to search, for example:
"Hattie B's".
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location to which the
search is to be restricted. The maximum is 50000 meters.
(default 3200)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
types -- A type to search against. See `types.py` "autocomplete types"
for complete list
https://developers.google.com/places/documentation/autocomplete#place_types.
components -- An optional grouping of places to which you would
like to restrict your results. An array containing one or
more tuples of:
* country: matches a country name or a two letter ISO 3166-1 country code.
eg: [('country','US')]
"""
self._request_params = {'input': input}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if types:
self._request_params['types'] = types
if len(components) > 0:
self._request_params['components'] = '|'.join(['{}:{}'.format(
c[0],c[1]) for c in components])
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.AUTOCOMPLETE_API_URL, self._request_params)
_validate_response(url, places_response)
return GoogleAutocompleteSearchResult(self, places_response)
def radar_search(self, sensor=False, keyword=None, name=None,
language=lang.ENGLISH, lat_lng=None, opennow=False,
radius=3200, type=None, types=[], location=None):
"""Perform a radar search using the Google Places API.
One of lat_lng or location are required, the rest of the keyword
arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
name -- A term to be matched against the names of Places. Results will
be restricted to those containing the passed name value.
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
opennow -- Returns only those Places that are open for business at the time
the query is sent. (default False)
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param
"""
if keyword is None and name is None and len(types) is 0:
raise ValueError('One of keyword, name or types must be supplied.')
if location is None and lat_lng is None:
raise ValueError('One of location or lat_lng must be passed in.')
try:
radius = int(radius)
except:
raise ValueError('radius must be passed supplied as an integer.')
if sensor not in [True, False]:
raise ValueError('sensor must be passed in as a boolean value.')
self._request_params = {'radius': radius}
self._sensor = sensor
self._request_params['location'] = self._generate_lat_lng_string(
lat_lng, location)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if opennow is True:
self._request_params['opennow'] = 'true'
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.RADAR_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def checkin(self, place_id, sensor=False):
"""Checks in a user to a place.
keyword arguments:
place_id -- The unique Google identifier for the relevant place.
sensor -- Boolean flag denoting if the location came from a
device using its location sensor (default False).
"""
data = {'placeid': place_id}
url, checkin_response = _fetch_remote_json(
GooglePlaces.CHECKIN_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(data), use_http_post=True)
_validate_response(url, checkin_response)
def get_place(self, place_id, sensor=False, language=lang.ENGLISH):
"""Gets a detailed place object.
keyword arguments:
place_id -- The unique Google identifier for the required place.
sensor -- Boolean flag denoting if the location came from a
device using its' location sensor (default False).
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
"""
place_details = _get_place_details(place_id,
self.api_key, sensor, language=language)
return Place(self, place_details)
def add_place(self, **kwargs):
"""Adds a place to the Google Places database.
On a successful request, this method will return a dict containing
the the new Place's place_id and id in keys 'place_id' and 'id'
respectively.
keyword arguments:
name -- The full text name of the Place. Limited to 255
characters.
lat_lng -- A dict containing the following keys: lat, lng.
accuracy -- The accuracy of the location signal on which this request
is based, expressed in meters.
types -- The category in which this Place belongs. Only one type
can currently be specified for a Place. A string or
single element list may be passed in.
language -- The language in which the Place's name is being reported.
(defaults 'en').
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
required_kwargs = {'name': [str], 'lat_lng': [dict],
'accuracy': [int], 'types': [str, list]}
request_params = {}
for key in required_kwargs:
if key not in kwargs or kwargs[key] is None:
raise ValueError('The %s argument is required.' % key)
expected_types = required_kwargs[key]
type_is_valid = False
for expected_type in expected_types:
if isinstance(kwargs[key], expected_type):
type_is_valid = True
break
if not type_is_valid:
raise ValueError('Invalid value for %s' % key)
if key is not 'lat_lng':
request_params[key] = kwargs[key]
if len(kwargs['name']) > 255:
raise ValueError('The place name must not exceed 255 characters ' +
'in length.')
try:
kwargs['lat_lng']['lat']
kwargs['lat_lng']['lng']
request_params['location'] = kwargs['lat_lng']
except KeyError:
raise ValueError('Invalid keys for lat_lng.')
request_params['language'] = (kwargs.get('language')
if kwargs.get('language') is not None else
lang.ENGLISH)
sensor = (kwargs.get('sensor')
if kwargs.get('sensor') is not None else
False)
# At some point Google might support multiple types, so this supports
# strings and lists.
if isinstance(kwargs['types'], str):
request_params['types'] = [kwargs['types']]
else:
request_params['types'] = kwargs['types']
url, add_response = _fetch_remote_json(
GooglePlaces.ADD_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, add_response)
return {'place_id': add_response['place_id'],
'id': add_response['id']}
def delete_place(self, place_id, sensor=False):
"""Deletes a place from the Google Places database.
keyword arguments:
place_id -- The textual identifier that uniquely identifies this
Place, returned from a Place Search request.
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
request_params = {'place_id': place_id}
url, delete_response = _fetch_remote_json(
GooglePlaces.DELETE_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, delete_response)
def _add_required_param_keys(self):
self._request_params['key'] = self.api_key
self._request_params['sensor'] = str(self.sensor).lower()
def _generate_lat_lng_string(self, lat_lng, location):
try:
return '%(lat)s,%(lng)s' % (lat_lng if lat_lng is not None
else geocode_location(location=location, api_key=self.api_key))
except GooglePlacesError as e:
raise ValueError(
'lat_lng must be a dict with the keys, \'lat\' and \'lng\'. Cause: %s' % str(e))
@property
def request_params(self):
return self._request_params
@property
def api_key(self):
return self._api_key
@property
def sensor(self):
return self._sensor
class GoogleAutocompleteSearchResult(object):
"""Wrapper around the Google Autocomplete API query JSON response."""
def __init__(self, query_instance, response):
self._response = response
self._predictions = []
for prediction in response['predictions']:
self._predictions.append(Prediction(query_instance, prediction))
@property
def raw_response(self):
"""Returns the raw JSON response returned by the Autocomplete API."""
return self._response
@property
def predictions(self):
return self._predictions
def __repr__(self):
"""Return a string representation stating number of predictions."""
return '<{} with {} prediction(s)>'.format(
self.__class__.__name__,
len(self.predictions)
)
class Prediction(object):
"""
Represents a prediction from the results of a Google Places Autocomplete API query.
"""
def __init__(self, query_instance, prediction):
self._query_instance = query_instance
self._description = prediction['description']
self._id = prediction['id']
self._matched_substrings = prediction['matched_substrings']
self._place_id = prediction['place_id']
self._reference = prediction['reference']
self._terms = prediction['terms']
self._types = prediction.get('types',[])
if prediction.get('_description') is None:
self._place = None
else:
self._place = prediction
@property
def description(self):
"""
String representation of a Prediction location. Generally contains
name, country, and elements contained in the terms property.
"""
return self._description
@property
def id(self):
"""
Returns the deprecated id property.
This identifier may not be used to retrieve information about this
place, but is guaranteed to be valid across sessions. It can be used
to consolidate data about this Place, and to verify the identity of a
Place across separate searches.
This property is deprecated:
https://developers.google.com/places/documentation/autocomplete#deprecation
"""
return self._id
@property
def matched_substrings(self):
"""
Returns the placement and offset of the matched strings for this search.
A an array of dicts, each with the keys 'length' and 'offset', will be returned.
"""
return self._matched_substrings
@property
def place_id(self):
"""
Returns the unique stable identifier denoting this place.
This identifier may be used to retrieve information about this
place.
This should be considered the primary identifier of a place.
"""
return self._place_id
@property
def reference(self):
"""
Returns the deprecated reference property.
The token can be used to retrieve additional information about this
place when invoking the getPlace method on an GooglePlaces instance.
You can store this token and use it at any time in future to refresh
cached data about this Place, but the same token is not guaranteed to
be returned for any given Place across different searches.
This property is deprecated:
https://developers.google.com/places/documentation/autocomplete#deprecation
"""
return self._reference
@property
def terms(self):
"""
A list of terms which build up the description string
A an array of dicts, each with the keys `offset` and `value`, will be returned.
"""
return self._terms
@property
def types(self):
"""
Returns a list of feature types describing the given result.
"""
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types
# The following properties require a further API call in order to be
# available.
@property
def place(self):
"""
Returns the JSON response from Google Places Detail search API.
"""
self._validate_status()
return self._place
def get_details(self, language=None):
"""
Retrieves full information on the place matching the place_id.
Stores the response in the `place` property.
"""
if self._place is None:
if language is None:
try:
language = self._query_instance._request_params['language']
except KeyError:
language = lang.ENGLISH
place = _get_place_details(
self.place_id, self._query_instance.api_key,
self._query_instance.sensor, language=language)
self._place = Place(self._query_instance, place)
def _validate_status(self):
"""
Indicates specific properties are only available after a details call.
"""
if self._place is None:
error_detail = ('The attribute requested is only available after ' +
'an explicit call to get_details() is made.')
raise GooglePlacesAttributeError(error_detail)
def __repr__(self):
""" Return a string representation with description. """
return '<{} description="{}">'.format(self.__class__.__name__, self.description)
class GooglePlacesSearchResult(object):
"""
Wrapper around the Google Places API query JSON response.
"""
def __init__(self, query_instance, response):
self._response = response
self._places = []
for place in response['results']:
self._places.append(Place(query_instance, place))
self._html_attributions = response.get('html_attributions', [])
self._next_page_token = response.get('next_page_token', [])
@property
def raw_response(self):
"""
Returns the raw JSON response returned by the Places API.
"""
return self._response
@property
def places(self):
return self._places
@property
def html_attributions(self):
"""Returns the HTML attributions for the specified response.
Any returned HTML attributions MUST be displayed as-is, in accordance
with the requirements as found in the documentation. Please see the
module comments for links to the relevant url.
"""
return self._html_attributions
@property
def next_page_token(self):
"""Returns the next page token(next_page_token)."""
return self._next_page_token
@property
def has_attributions(self):
"""Returns a flag denoting if the response had any html attributions."""
return len(self.html_attributions) > 0
@property
def has_next_page_token(self):
"""Returns a flag denoting if the response had a next page token."""
return len(self.next_page_token) > 0
def __repr__(self):
""" Return a string representation stating the number of results."""
return '<{} with {} result(s)>'.format(self.__class__.__name__, len(self.places))
class Place(object):
"""
Represents a place from the results of a Google Places API query.
"""
def __init__(self, query_instance, place_data):
self._query_instance = query_instance
self._place_id = place_data['place_id']
self._id = place_data.get('id', '')
self._reference = place_data.get('reference', '')
self._name = place_data.get('name','')
self._vicinity = place_data.get('vicinity', '')
self._geo_location = place_data['geometry']['location']
self._rating = place_data.get('rating','')
self._types = place_data.get('types','')
self._icon = place_data.get('icon','')
if place_data.get('address_components') is None:
self._details = None
else:
self._details = place_data
@property
def reference(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns contains a unique token for the place.
The token can be used to retrieve additional information about this
place when invoking the getPlace method on an GooglePlaces instance.
You can store this token and use it at any time in future to refresh
cached data about this Place, but the same token is not guaranteed to
be returned for any given Place across different searches."""
warnings.warn('The "reference" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._reference
@property
def id(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns the unique stable identifier denoting this place.
This identifier may not be used to retrieve information about this
place, but is guaranteed to be valid across sessions. It can be used
to consolidate data about this Place, and to verify the identity of a
Place across separate searches.
"""
warnings.warn('The "id" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._id
@property
def place_id(self):
"""Returns the unique stable identifier denoting this place.
This identifier may be used to retrieve information about this
place.
This should be considered the primary identifier of a place.
"""
return self._place_id
@property
def icon(self):
"""Returns the URL of a recommended icon for display."""
if self._icon == '' and self.details != None and 'icon' in self.details:
self._icon = self.details['icon']
return self._icon
@property
def types(self):
"""Returns a list of feature types describing the given result."""
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types
@property
def geo_location(self):
"""Returns the lat lng co-ordinates of the place.
A dict with the keys 'lat' and 'lng' will be returned.
"""
return self._geo_location
@property
def name(self):
"""Returns the human-readable name of the place."""
if self._name == '' and self.details != None and 'name' in self.details:
self._name = self.details['name']
return self._name
@property
def vicinity(self):
"""Returns a feature name of a nearby location.
Often this feature refers to a street or neighborhood within the given
results.
"""
if self._vicinity == '' and self.details != None and 'vicinity' in self.details:
self._vicinity = self.details['vicinity']
return self._vicinity
@property
def rating(self):
"""Returns the Place's rating, from 0.0 to 5.0, based on user reviews.
This method will return None for places that have no rating.
"""
if self._rating == '' and self.details != None and 'rating' in self.details:
self._rating = self.details['rating']
return self._rating
# The following properties require a further API call in order to be
# available.
@property
def details(self):
"""Returns the JSON response from Google Places Detail search API."""
self._validate_status()
return self._details
@property
def formatted_address(self):
"""Returns a string containing the human-readable address of this place.
Often this address is equivalent to the "postal address," which
sometimes differs from country to country. (Note that some countries,
such as the United Kingdom, do not allow distribution of complete postal
addresses due to licensing restrictions.)
"""
self._validate_status()
return self.details.get('formatted_address')
@property
def local_phone_number(self):
"""Returns the Place's phone number in its local format."""
self._validate_status()
return self.details.get('formatted_phone_number')
@property
def international_phone_number(self):
self._validate_status()
return self.details.get('international_phone_number')
@property
def website(self):
"""Returns the authoritative website for this Place."""
self._validate_status()
return self.details.get('website')
@property
def url(self):
"""Contains the official Google Place Page URL of this establishment.
Applications must link to or embed the Google Place page on any screen
that shows detailed results about this Place to the user.
"""
self._validate_status()
return self.details.get('url')
@property
def html_attributions(self):
"""Returns the HTML attributions for the specified response.
Any returned HTML attributions MUST be displayed as-is, in accordance
with the requirements as found in the documentation. Please see the
module comments for links to the relevant url.
"""
self._validate_status()
return self.details.get('html_attributions', [])
@property
def has_attributions(self):
"""Returns a flag denoting if the response had any html attributions."""
return (False if self._details is None else
len(self.html_attributions) > 0)
def checkin(self):
"""Checks in an anonymous user in."""
self._query_instance.checkin(self.place_id,
self._query_instance.sensor)
def get_details(self, language=None):
"""Retrieves full information on the place matching the place_id.
Further attributes will be made available on the instance once this
method has been invoked.
keyword arguments:
language -- The language code, indicating in which language the
results should be returned, if possible. This value defaults
to the language that was used to generate the
GooglePlacesSearchResult instance.
"""
if self._details is None:
if language is None:
try:
language = self._query_instance._request_params['language']
except KeyError:
language = lang.ENGLISH
self._details = _get_place_details(
self.place_id, self._query_instance.api_key,
self._query_instance.sensor, language=language)
@cached_property
def photos(self):
self.get_details()
return [Photo(self._query_instance, i)
for i in self.details.get('photos', [])]
def _validate_status(self):
if self._details is None:
error_detail = ('The attribute requested is only available after ' +
'an explicit call to get_details() is made.')
raise GooglePlacesAttributeError(error_detail)
def __repr__(self):
""" Return a string representation including the name, lat, and lng. """
return '<{} name="{}", lat={}, lng={}>'.format(
self.__class__.__name__,
self.name,
self.geo_location['lat'],
self.geo_location['lng']
)
class Photo(object):
def __init__(self, query_instance, attrs):
self._query_instance = query_instance
self.orig_height = attrs.get('height')
self.orig_width = attrs.get('width')
self.html_attributions = attrs.get('html_attributions')
self.photo_reference = attrs.get('photo_reference')
def get(self, maxheight=None, maxwidth=None, sensor=False):
"""Fetch photo from API."""
if not maxheight and not maxwidth:
raise GooglePlacesError('You must specify maxheight or maxwidth!')
result = _get_place_photo(self.photo_reference,
self._query_instance.api_key,
maxheight=maxheight, maxwidth=maxwidth,
sensor=sensor)
self.mimetype, self.filename, self.data, self.url = result
|
slimkrazy/python-google-places | googleplaces/__init__.py | _get_place_details | python | def _get_place_details(place_id, api_key, sensor=False,
language=lang.ENGLISH):
url, detail_response = _fetch_remote_json(GooglePlaces.DETAIL_API_URL,
{'placeid': place_id,
'sensor': str(sensor).lower(),
'key': api_key,
'language': language})
_validate_response(url, detail_response)
return detail_response['result'] | Gets a detailed place response.
keyword arguments:
place_id -- The unique identifier for the required place. | train | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L126-L139 | [
"def _fetch_remote_json(service_url, params=None, use_http_post=False):\n \"\"\"Retrieves a JSON object from a URL.\"\"\"\n if not params:\n params = {}\n\n request_url, response = _fetch_remote(service_url, params, use_http_post)\n if six.PY3:\n str_response = response.read().decode('utf-... | """
A simple wrapper around the 'experimental' Google Places API, documented
here: http://code.google.com/apis/maps/documentation/places/. This library
also makes use of the v3 Maps API for geocoding.
Prerequisites: A Google API key with Places activated against it. Please
check the Google API console, here: http://code.google.com/apis/console
NOTE: Please ensure that you read the Google terms of service (labelled 'Limits
and Requirements' on the documentation url) prior to using this library in a
production environment.
@author: sam@slimkrazy.com
"""
from __future__ import absolute_import
import cgi
from decimal import Decimal
try:
import json
except ImportError:
import simplejson as json
try:
import six
from six.moves import urllib
except ImportError:
pass
import warnings
from . import lang
from . import ranking
__all__ = ['GooglePlaces', 'GooglePlacesError', 'GooglePlacesAttributeError',
'geocode_location']
__version__ = '1.4.1'
__author__ = 'Samuel Adu'
__email__ = 'sam@slimkrazy.com'
class cached_property(object):
def __init__(self, func):
self.func = func
def __get__(self, instance, cls=None):
result = instance.__dict__[self.func.__name__] = self.func(instance)
return result
def _fetch_remote(service_url, params=None, use_http_post=False):
if not params:
params = {}
encoded_data = {}
for k, v in params.items():
if isinstance(v, six.string_types):
v = v.encode('utf-8')
encoded_data[k] = v
encoded_data = urllib.parse.urlencode(encoded_data)
if not use_http_post:
query_url = (service_url if service_url.endswith('?') else
'%s?' % service_url)
request_url = query_url + encoded_data
request = urllib.request.Request(request_url)
else:
request_url = service_url
request = urllib.request.Request(service_url, data=encoded_data)
return (request_url, urllib.request.urlopen(request))
def _fetch_remote_json(service_url, params=None, use_http_post=False):
"""Retrieves a JSON object from a URL."""
if not params:
params = {}
request_url, response = _fetch_remote(service_url, params, use_http_post)
if six.PY3:
str_response = response.read().decode('utf-8')
return (request_url, json.loads(str_response, parse_float=Decimal))
return (request_url, json.load(response, parse_float=Decimal))
def _fetch_remote_file(service_url, params=None, use_http_post=False):
"""Retrieves a file from a URL.
Returns a tuple (mimetype, filename, data)
"""
if not params:
params = {}
request_url, response = _fetch_remote(service_url, params, use_http_post)
dummy, params = cgi.parse_header(
response.headers.get('Content-Disposition', ''))
fn = params['filename']
return (response.headers.get('content-type'),
fn, response.read(), response.geturl())
def geocode_location(location, sensor=False, api_key=None):
"""Converts a human-readable location to lat-lng.
Returns a dict with lat and lng keys.
keyword arguments:
location -- A human-readable location, e.g 'London, England'
sensor -- Boolean flag denoting if the location came from a device using
its' location sensor (default False)
api_key -- A valid Google Places API key.
raises:
GooglePlacesError -- if the geocoder fails to find a location.
"""
params = {'address': location, 'sensor': str(sensor).lower()}
if api_key is not None:
params['key'] = api_key
url, geo_response = _fetch_remote_json(
GooglePlaces.GEOCODE_API_URL, params)
_validate_response(url, geo_response)
if geo_response['status'] == GooglePlaces.RESPONSE_STATUS_ZERO_RESULTS:
error_detail = ('Lat/Lng for location \'%s\' can\'t be determined.' %
location)
raise GooglePlacesError(error_detail)
return geo_response['results'][0]['geometry']['location']
def _get_place_photo(photoreference, api_key, maxheight=None, maxwidth=None,
sensor=False):
"""Gets a place's photo by reference.
See detailed documentation at https://developers.google.com/places/documentation/photos
Arguments:
photoreference -- The unique Google reference for the required photo.
Keyword arguments:
maxheight -- The maximum desired photo height in pixels
maxwidth -- The maximum desired photo width in pixels
You must specify one of this keyword arguments. Acceptable value is an
integer between 1 and 1600.
"""
params = {'photoreference': photoreference,
'sensor': str(sensor).lower(),
'key': api_key}
if maxheight:
params['maxheight'] = maxheight
if maxwidth:
params['maxwidth'] = maxwidth
return _fetch_remote_file(GooglePlaces.PHOTO_API_URL, params)
def _validate_response(url, response):
"""Validates that the response from Google was successful."""
if response['status'] not in [GooglePlaces.RESPONSE_STATUS_OK,
GooglePlaces.RESPONSE_STATUS_ZERO_RESULTS]:
error_detail = ('Request to URL %s failed with response code: %s' %
(url, response['status']))
raise GooglePlacesError(error_detail)
class GooglePlacesError(Exception):
pass
class GooglePlacesAttributeError(AttributeError):
"""Exception thrown when a detailed property is unavailable.
A search query from the places API returns only a summary of the Place.
in order to get full details, a further API call must be made using
the place_id. This exception will be thrown when a property made
available by only the detailed API call is looked up against the summary
object.
An explicit call to get_details() must be made on the summary object in
order to convert a summary object to a detailed object.
"""
# I could spend forever muling between this design decision and creating
# a PlaceSummary object as well as a Place object. I'm leaning towards this
# method in order to keep the API as simple as possible.
pass
class GooglePlaces(object):
"""A wrapper around the Google Places Query API."""
BASE_URL = 'https://maps.googleapis.com/maps/api'
PLACE_URL = BASE_URL + '/place'
GEOCODE_API_URL = BASE_URL + '/geocode/json?'
RADAR_SEARCH_API_URL = PLACE_URL + '/radarsearch/json?'
NEARBY_SEARCH_API_URL = PLACE_URL + '/nearbysearch/json?'
TEXT_SEARCH_API_URL = PLACE_URL + '/textsearch/json?'
AUTOCOMPLETE_API_URL = PLACE_URL + '/autocomplete/json?'
DETAIL_API_URL = PLACE_URL + '/details/json?'
CHECKIN_API_URL = PLACE_URL + '/check-in/json?sensor=%s&key=%s'
ADD_API_URL = PLACE_URL + '/add/json?sensor=%s&key=%s'
DELETE_API_URL = PLACE_URL + '/delete/json?sensor=%s&key=%s'
PHOTO_API_URL = PLACE_URL + '/photo?'
MAXIMUM_SEARCH_RADIUS = 50000
RESPONSE_STATUS_OK = 'OK'
RESPONSE_STATUS_ZERO_RESULTS = 'ZERO_RESULTS'
def __init__(self, api_key):
self._api_key = api_key
self._sensor = False
self._request_params = None
def query(self, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter('always')
warnings.warn('The query API is deprecated. Please use nearby_search.',
DeprecationWarning, stacklevel=2)
return self.nearby_search(**kwargs)
def nearby_search(self, language=lang.ENGLISH, keyword=None, location=None,
lat_lng=None, name=None, radius=3200, rankby=ranking.PROMINENCE,
sensor=False, type=None, types=[], pagetoken=None):
"""Perform a nearby search using the Google Places API.
One of either location, lat_lng or pagetoken are required, the rest of
the keyword arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
location -- A human readable location, e.g 'London, England'
(default None)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
name -- A term to be matched against the names of the Places.
Results will be restricted to those containing the passed
name value. (default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
rankby -- Specifies the order in which results are listed :
ranking.PROMINENCE (default) or ranking.DISTANCE
(imply no radius argument).
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
"""
if location is None and lat_lng is None and pagetoken is None:
raise ValueError('One of location, lat_lng or pagetoken must be passed in.')
if rankby == 'distance':
# As per API docs rankby == distance:
# One or more of keyword, name, or types is required.
if keyword is None and types == [] and name is None:
raise ValueError('When rankby = googleplaces.ranking.DISTANCE, ' +
'name, keyword or types kwargs ' +
'must be specified.')
self._sensor = sensor
radius = (radius if radius <= GooglePlaces.MAXIMUM_SEARCH_RADIUS
else GooglePlaces.MAXIMUM_SEARCH_RADIUS)
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params = {'location': lat_lng_str}
if rankby == 'prominence':
self._request_params['radius'] = radius
else:
self._request_params['rankby'] = rankby
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.NEARBY_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def text_search(self, query=None, language=lang.ENGLISH, lat_lng=None,
radius=3200, type=None, types=[], location=None, pagetoken=None):
"""Perform a text search using the Google Places API.
Only the one of the query or pagetoken kwargs are required, the rest of the
keyword arguments are optional.
keyword arguments:
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
query -- The text string on which to search, for example:
"Restaurant in New York".
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
"""
self._request_params = {'query': query}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.TEXT_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def autocomplete(self, input, lat_lng=None, location=None, radius=3200,
language=lang.ENGLISH, types=None, components=[]):
"""
Perform an autocomplete search using the Google Places API.
Only the input kwarg is required, the rest of the keyword arguments
are optional.
keyword arguments:
input -- The text string on which to search, for example:
"Hattie B's".
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location to which the
search is to be restricted. The maximum is 50000 meters.
(default 3200)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
types -- A type to search against. See `types.py` "autocomplete types"
for complete list
https://developers.google.com/places/documentation/autocomplete#place_types.
components -- An optional grouping of places to which you would
like to restrict your results. An array containing one or
more tuples of:
* country: matches a country name or a two letter ISO 3166-1 country code.
eg: [('country','US')]
"""
self._request_params = {'input': input}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if types:
self._request_params['types'] = types
if len(components) > 0:
self._request_params['components'] = '|'.join(['{}:{}'.format(
c[0],c[1]) for c in components])
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.AUTOCOMPLETE_API_URL, self._request_params)
_validate_response(url, places_response)
return GoogleAutocompleteSearchResult(self, places_response)
def radar_search(self, sensor=False, keyword=None, name=None,
language=lang.ENGLISH, lat_lng=None, opennow=False,
radius=3200, type=None, types=[], location=None):
"""Perform a radar search using the Google Places API.
One of lat_lng or location are required, the rest of the keyword
arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
name -- A term to be matched against the names of Places. Results will
be restricted to those containing the passed name value.
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
opennow -- Returns only those Places that are open for business at the time
the query is sent. (default False)
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param
"""
if keyword is None and name is None and len(types) is 0:
raise ValueError('One of keyword, name or types must be supplied.')
if location is None and lat_lng is None:
raise ValueError('One of location or lat_lng must be passed in.')
try:
radius = int(radius)
except:
raise ValueError('radius must be passed supplied as an integer.')
if sensor not in [True, False]:
raise ValueError('sensor must be passed in as a boolean value.')
self._request_params = {'radius': radius}
self._sensor = sensor
self._request_params['location'] = self._generate_lat_lng_string(
lat_lng, location)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if opennow is True:
self._request_params['opennow'] = 'true'
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.RADAR_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def checkin(self, place_id, sensor=False):
"""Checks in a user to a place.
keyword arguments:
place_id -- The unique Google identifier for the relevant place.
sensor -- Boolean flag denoting if the location came from a
device using its location sensor (default False).
"""
data = {'placeid': place_id}
url, checkin_response = _fetch_remote_json(
GooglePlaces.CHECKIN_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(data), use_http_post=True)
_validate_response(url, checkin_response)
def get_place(self, place_id, sensor=False, language=lang.ENGLISH):
"""Gets a detailed place object.
keyword arguments:
place_id -- The unique Google identifier for the required place.
sensor -- Boolean flag denoting if the location came from a
device using its' location sensor (default False).
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
"""
place_details = _get_place_details(place_id,
self.api_key, sensor, language=language)
return Place(self, place_details)
def add_place(self, **kwargs):
"""Adds a place to the Google Places database.
On a successful request, this method will return a dict containing
the the new Place's place_id and id in keys 'place_id' and 'id'
respectively.
keyword arguments:
name -- The full text name of the Place. Limited to 255
characters.
lat_lng -- A dict containing the following keys: lat, lng.
accuracy -- The accuracy of the location signal on which this request
is based, expressed in meters.
types -- The category in which this Place belongs. Only one type
can currently be specified for a Place. A string or
single element list may be passed in.
language -- The language in which the Place's name is being reported.
(defaults 'en').
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
required_kwargs = {'name': [str], 'lat_lng': [dict],
'accuracy': [int], 'types': [str, list]}
request_params = {}
for key in required_kwargs:
if key not in kwargs or kwargs[key] is None:
raise ValueError('The %s argument is required.' % key)
expected_types = required_kwargs[key]
type_is_valid = False
for expected_type in expected_types:
if isinstance(kwargs[key], expected_type):
type_is_valid = True
break
if not type_is_valid:
raise ValueError('Invalid value for %s' % key)
if key is not 'lat_lng':
request_params[key] = kwargs[key]
if len(kwargs['name']) > 255:
raise ValueError('The place name must not exceed 255 characters ' +
'in length.')
try:
kwargs['lat_lng']['lat']
kwargs['lat_lng']['lng']
request_params['location'] = kwargs['lat_lng']
except KeyError:
raise ValueError('Invalid keys for lat_lng.')
request_params['language'] = (kwargs.get('language')
if kwargs.get('language') is not None else
lang.ENGLISH)
sensor = (kwargs.get('sensor')
if kwargs.get('sensor') is not None else
False)
# At some point Google might support multiple types, so this supports
# strings and lists.
if isinstance(kwargs['types'], str):
request_params['types'] = [kwargs['types']]
else:
request_params['types'] = kwargs['types']
url, add_response = _fetch_remote_json(
GooglePlaces.ADD_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, add_response)
return {'place_id': add_response['place_id'],
'id': add_response['id']}
def delete_place(self, place_id, sensor=False):
"""Deletes a place from the Google Places database.
keyword arguments:
place_id -- The textual identifier that uniquely identifies this
Place, returned from a Place Search request.
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
request_params = {'place_id': place_id}
url, delete_response = _fetch_remote_json(
GooglePlaces.DELETE_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, delete_response)
def _add_required_param_keys(self):
self._request_params['key'] = self.api_key
self._request_params['sensor'] = str(self.sensor).lower()
def _generate_lat_lng_string(self, lat_lng, location):
try:
return '%(lat)s,%(lng)s' % (lat_lng if lat_lng is not None
else geocode_location(location=location, api_key=self.api_key))
except GooglePlacesError as e:
raise ValueError(
'lat_lng must be a dict with the keys, \'lat\' and \'lng\'. Cause: %s' % str(e))
@property
def request_params(self):
return self._request_params
@property
def api_key(self):
return self._api_key
@property
def sensor(self):
return self._sensor
class GoogleAutocompleteSearchResult(object):
"""Wrapper around the Google Autocomplete API query JSON response."""
def __init__(self, query_instance, response):
self._response = response
self._predictions = []
for prediction in response['predictions']:
self._predictions.append(Prediction(query_instance, prediction))
@property
def raw_response(self):
"""Returns the raw JSON response returned by the Autocomplete API."""
return self._response
@property
def predictions(self):
return self._predictions
def __repr__(self):
"""Return a string representation stating number of predictions."""
return '<{} with {} prediction(s)>'.format(
self.__class__.__name__,
len(self.predictions)
)
class Prediction(object):
"""
Represents a prediction from the results of a Google Places Autocomplete API query.
"""
def __init__(self, query_instance, prediction):
self._query_instance = query_instance
self._description = prediction['description']
self._id = prediction['id']
self._matched_substrings = prediction['matched_substrings']
self._place_id = prediction['place_id']
self._reference = prediction['reference']
self._terms = prediction['terms']
self._types = prediction.get('types',[])
if prediction.get('_description') is None:
self._place = None
else:
self._place = prediction
@property
def description(self):
"""
String representation of a Prediction location. Generally contains
name, country, and elements contained in the terms property.
"""
return self._description
@property
def id(self):
"""
Returns the deprecated id property.
This identifier may not be used to retrieve information about this
place, but is guaranteed to be valid across sessions. It can be used
to consolidate data about this Place, and to verify the identity of a
Place across separate searches.
This property is deprecated:
https://developers.google.com/places/documentation/autocomplete#deprecation
"""
return self._id
@property
def matched_substrings(self):
"""
Returns the placement and offset of the matched strings for this search.
A an array of dicts, each with the keys 'length' and 'offset', will be returned.
"""
return self._matched_substrings
@property
def place_id(self):
"""
Returns the unique stable identifier denoting this place.
This identifier may be used to retrieve information about this
place.
This should be considered the primary identifier of a place.
"""
return self._place_id
@property
def reference(self):
"""
Returns the deprecated reference property.
The token can be used to retrieve additional information about this
place when invoking the getPlace method on an GooglePlaces instance.
You can store this token and use it at any time in future to refresh
cached data about this Place, but the same token is not guaranteed to
be returned for any given Place across different searches.
This property is deprecated:
https://developers.google.com/places/documentation/autocomplete#deprecation
"""
return self._reference
@property
def terms(self):
"""
A list of terms which build up the description string
A an array of dicts, each with the keys `offset` and `value`, will be returned.
"""
return self._terms
@property
def types(self):
"""
Returns a list of feature types describing the given result.
"""
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types
# The following properties require a further API call in order to be
# available.
@property
def place(self):
"""
Returns the JSON response from Google Places Detail search API.
"""
self._validate_status()
return self._place
def get_details(self, language=None):
"""
Retrieves full information on the place matching the place_id.
Stores the response in the `place` property.
"""
if self._place is None:
if language is None:
try:
language = self._query_instance._request_params['language']
except KeyError:
language = lang.ENGLISH
place = _get_place_details(
self.place_id, self._query_instance.api_key,
self._query_instance.sensor, language=language)
self._place = Place(self._query_instance, place)
def _validate_status(self):
"""
Indicates specific properties are only available after a details call.
"""
if self._place is None:
error_detail = ('The attribute requested is only available after ' +
'an explicit call to get_details() is made.')
raise GooglePlacesAttributeError(error_detail)
def __repr__(self):
""" Return a string representation with description. """
return '<{} description="{}">'.format(self.__class__.__name__, self.description)
class GooglePlacesSearchResult(object):
"""
Wrapper around the Google Places API query JSON response.
"""
def __init__(self, query_instance, response):
self._response = response
self._places = []
for place in response['results']:
self._places.append(Place(query_instance, place))
self._html_attributions = response.get('html_attributions', [])
self._next_page_token = response.get('next_page_token', [])
@property
def raw_response(self):
"""
Returns the raw JSON response returned by the Places API.
"""
return self._response
@property
def places(self):
return self._places
@property
def html_attributions(self):
"""Returns the HTML attributions for the specified response.
Any returned HTML attributions MUST be displayed as-is, in accordance
with the requirements as found in the documentation. Please see the
module comments for links to the relevant url.
"""
return self._html_attributions
@property
def next_page_token(self):
"""Returns the next page token(next_page_token)."""
return self._next_page_token
@property
def has_attributions(self):
"""Returns a flag denoting if the response had any html attributions."""
return len(self.html_attributions) > 0
@property
def has_next_page_token(self):
"""Returns a flag denoting if the response had a next page token."""
return len(self.next_page_token) > 0
def __repr__(self):
""" Return a string representation stating the number of results."""
return '<{} with {} result(s)>'.format(self.__class__.__name__, len(self.places))
class Place(object):
"""
Represents a place from the results of a Google Places API query.
"""
def __init__(self, query_instance, place_data):
self._query_instance = query_instance
self._place_id = place_data['place_id']
self._id = place_data.get('id', '')
self._reference = place_data.get('reference', '')
self._name = place_data.get('name','')
self._vicinity = place_data.get('vicinity', '')
self._geo_location = place_data['geometry']['location']
self._rating = place_data.get('rating','')
self._types = place_data.get('types','')
self._icon = place_data.get('icon','')
if place_data.get('address_components') is None:
self._details = None
else:
self._details = place_data
@property
def reference(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns contains a unique token for the place.
The token can be used to retrieve additional information about this
place when invoking the getPlace method on an GooglePlaces instance.
You can store this token and use it at any time in future to refresh
cached data about this Place, but the same token is not guaranteed to
be returned for any given Place across different searches."""
warnings.warn('The "reference" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._reference
@property
def id(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns the unique stable identifier denoting this place.
This identifier may not be used to retrieve information about this
place, but is guaranteed to be valid across sessions. It can be used
to consolidate data about this Place, and to verify the identity of a
Place across separate searches.
"""
warnings.warn('The "id" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._id
@property
def place_id(self):
"""Returns the unique stable identifier denoting this place.
This identifier may be used to retrieve information about this
place.
This should be considered the primary identifier of a place.
"""
return self._place_id
@property
def icon(self):
"""Returns the URL of a recommended icon for display."""
if self._icon == '' and self.details != None and 'icon' in self.details:
self._icon = self.details['icon']
return self._icon
@property
def types(self):
"""Returns a list of feature types describing the given result."""
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types
@property
def geo_location(self):
"""Returns the lat lng co-ordinates of the place.
A dict with the keys 'lat' and 'lng' will be returned.
"""
return self._geo_location
@property
def name(self):
"""Returns the human-readable name of the place."""
if self._name == '' and self.details != None and 'name' in self.details:
self._name = self.details['name']
return self._name
@property
def vicinity(self):
"""Returns a feature name of a nearby location.
Often this feature refers to a street or neighborhood within the given
results.
"""
if self._vicinity == '' and self.details != None and 'vicinity' in self.details:
self._vicinity = self.details['vicinity']
return self._vicinity
@property
def rating(self):
"""Returns the Place's rating, from 0.0 to 5.0, based on user reviews.
This method will return None for places that have no rating.
"""
if self._rating == '' and self.details != None and 'rating' in self.details:
self._rating = self.details['rating']
return self._rating
# The following properties require a further API call in order to be
# available.
@property
def details(self):
"""Returns the JSON response from Google Places Detail search API."""
self._validate_status()
return self._details
@property
def formatted_address(self):
"""Returns a string containing the human-readable address of this place.
Often this address is equivalent to the "postal address," which
sometimes differs from country to country. (Note that some countries,
such as the United Kingdom, do not allow distribution of complete postal
addresses due to licensing restrictions.)
"""
self._validate_status()
return self.details.get('formatted_address')
@property
def local_phone_number(self):
"""Returns the Place's phone number in its local format."""
self._validate_status()
return self.details.get('formatted_phone_number')
@property
def international_phone_number(self):
self._validate_status()
return self.details.get('international_phone_number')
@property
def website(self):
"""Returns the authoritative website for this Place."""
self._validate_status()
return self.details.get('website')
@property
def url(self):
"""Contains the official Google Place Page URL of this establishment.
Applications must link to or embed the Google Place page on any screen
that shows detailed results about this Place to the user.
"""
self._validate_status()
return self.details.get('url')
@property
def html_attributions(self):
"""Returns the HTML attributions for the specified response.
Any returned HTML attributions MUST be displayed as-is, in accordance
with the requirements as found in the documentation. Please see the
module comments for links to the relevant url.
"""
self._validate_status()
return self.details.get('html_attributions', [])
@property
def has_attributions(self):
"""Returns a flag denoting if the response had any html attributions."""
return (False if self._details is None else
len(self.html_attributions) > 0)
def checkin(self):
"""Checks in an anonymous user in."""
self._query_instance.checkin(self.place_id,
self._query_instance.sensor)
def get_details(self, language=None):
"""Retrieves full information on the place matching the place_id.
Further attributes will be made available on the instance once this
method has been invoked.
keyword arguments:
language -- The language code, indicating in which language the
results should be returned, if possible. This value defaults
to the language that was used to generate the
GooglePlacesSearchResult instance.
"""
if self._details is None:
if language is None:
try:
language = self._query_instance._request_params['language']
except KeyError:
language = lang.ENGLISH
self._details = _get_place_details(
self.place_id, self._query_instance.api_key,
self._query_instance.sensor, language=language)
@cached_property
def photos(self):
self.get_details()
return [Photo(self._query_instance, i)
for i in self.details.get('photos', [])]
def _validate_status(self):
if self._details is None:
error_detail = ('The attribute requested is only available after ' +
'an explicit call to get_details() is made.')
raise GooglePlacesAttributeError(error_detail)
def __repr__(self):
""" Return a string representation including the name, lat, and lng. """
return '<{} name="{}", lat={}, lng={}>'.format(
self.__class__.__name__,
self.name,
self.geo_location['lat'],
self.geo_location['lng']
)
class Photo(object):
def __init__(self, query_instance, attrs):
self._query_instance = query_instance
self.orig_height = attrs.get('height')
self.orig_width = attrs.get('width')
self.html_attributions = attrs.get('html_attributions')
self.photo_reference = attrs.get('photo_reference')
def get(self, maxheight=None, maxwidth=None, sensor=False):
"""Fetch photo from API."""
if not maxheight and not maxwidth:
raise GooglePlacesError('You must specify maxheight or maxwidth!')
result = _get_place_photo(self.photo_reference,
self._query_instance.api_key,
maxheight=maxheight, maxwidth=maxwidth,
sensor=sensor)
self.mimetype, self.filename, self.data, self.url = result
|
slimkrazy/python-google-places | googleplaces/__init__.py | _get_place_photo | python | def _get_place_photo(photoreference, api_key, maxheight=None, maxwidth=None,
sensor=False):
params = {'photoreference': photoreference,
'sensor': str(sensor).lower(),
'key': api_key}
if maxheight:
params['maxheight'] = maxheight
if maxwidth:
params['maxwidth'] = maxwidth
return _fetch_remote_file(GooglePlaces.PHOTO_API_URL, params) | Gets a place's photo by reference.
See detailed documentation at https://developers.google.com/places/documentation/photos
Arguments:
photoreference -- The unique Google reference for the required photo.
Keyword arguments:
maxheight -- The maximum desired photo height in pixels
maxwidth -- The maximum desired photo width in pixels
You must specify one of this keyword arguments. Acceptable value is an
integer between 1 and 1600. | train | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L141-L167 | [
"def _fetch_remote_file(service_url, params=None, use_http_post=False):\n \"\"\"Retrieves a file from a URL.\n\n Returns a tuple (mimetype, filename, data)\n \"\"\"\n if not params:\n params = {}\n\n request_url, response = _fetch_remote(service_url, params, use_http_post)\n dummy, params =... | """
A simple wrapper around the 'experimental' Google Places API, documented
here: http://code.google.com/apis/maps/documentation/places/. This library
also makes use of the v3 Maps API for geocoding.
Prerequisites: A Google API key with Places activated against it. Please
check the Google API console, here: http://code.google.com/apis/console
NOTE: Please ensure that you read the Google terms of service (labelled 'Limits
and Requirements' on the documentation url) prior to using this library in a
production environment.
@author: sam@slimkrazy.com
"""
from __future__ import absolute_import
import cgi
from decimal import Decimal
try:
import json
except ImportError:
import simplejson as json
try:
import six
from six.moves import urllib
except ImportError:
pass
import warnings
from . import lang
from . import ranking
__all__ = ['GooglePlaces', 'GooglePlacesError', 'GooglePlacesAttributeError',
'geocode_location']
__version__ = '1.4.1'
__author__ = 'Samuel Adu'
__email__ = 'sam@slimkrazy.com'
class cached_property(object):
def __init__(self, func):
self.func = func
def __get__(self, instance, cls=None):
result = instance.__dict__[self.func.__name__] = self.func(instance)
return result
def _fetch_remote(service_url, params=None, use_http_post=False):
if not params:
params = {}
encoded_data = {}
for k, v in params.items():
if isinstance(v, six.string_types):
v = v.encode('utf-8')
encoded_data[k] = v
encoded_data = urllib.parse.urlencode(encoded_data)
if not use_http_post:
query_url = (service_url if service_url.endswith('?') else
'%s?' % service_url)
request_url = query_url + encoded_data
request = urllib.request.Request(request_url)
else:
request_url = service_url
request = urllib.request.Request(service_url, data=encoded_data)
return (request_url, urllib.request.urlopen(request))
def _fetch_remote_json(service_url, params=None, use_http_post=False):
"""Retrieves a JSON object from a URL."""
if not params:
params = {}
request_url, response = _fetch_remote(service_url, params, use_http_post)
if six.PY3:
str_response = response.read().decode('utf-8')
return (request_url, json.loads(str_response, parse_float=Decimal))
return (request_url, json.load(response, parse_float=Decimal))
def _fetch_remote_file(service_url, params=None, use_http_post=False):
"""Retrieves a file from a URL.
Returns a tuple (mimetype, filename, data)
"""
if not params:
params = {}
request_url, response = _fetch_remote(service_url, params, use_http_post)
dummy, params = cgi.parse_header(
response.headers.get('Content-Disposition', ''))
fn = params['filename']
return (response.headers.get('content-type'),
fn, response.read(), response.geturl())
def geocode_location(location, sensor=False, api_key=None):
"""Converts a human-readable location to lat-lng.
Returns a dict with lat and lng keys.
keyword arguments:
location -- A human-readable location, e.g 'London, England'
sensor -- Boolean flag denoting if the location came from a device using
its' location sensor (default False)
api_key -- A valid Google Places API key.
raises:
GooglePlacesError -- if the geocoder fails to find a location.
"""
params = {'address': location, 'sensor': str(sensor).lower()}
if api_key is not None:
params['key'] = api_key
url, geo_response = _fetch_remote_json(
GooglePlaces.GEOCODE_API_URL, params)
_validate_response(url, geo_response)
if geo_response['status'] == GooglePlaces.RESPONSE_STATUS_ZERO_RESULTS:
error_detail = ('Lat/Lng for location \'%s\' can\'t be determined.' %
location)
raise GooglePlacesError(error_detail)
return geo_response['results'][0]['geometry']['location']
def _get_place_details(place_id, api_key, sensor=False,
language=lang.ENGLISH):
"""Gets a detailed place response.
keyword arguments:
place_id -- The unique identifier for the required place.
"""
url, detail_response = _fetch_remote_json(GooglePlaces.DETAIL_API_URL,
{'placeid': place_id,
'sensor': str(sensor).lower(),
'key': api_key,
'language': language})
_validate_response(url, detail_response)
return detail_response['result']
def _validate_response(url, response):
"""Validates that the response from Google was successful."""
if response['status'] not in [GooglePlaces.RESPONSE_STATUS_OK,
GooglePlaces.RESPONSE_STATUS_ZERO_RESULTS]:
error_detail = ('Request to URL %s failed with response code: %s' %
(url, response['status']))
raise GooglePlacesError(error_detail)
class GooglePlacesError(Exception):
pass
class GooglePlacesAttributeError(AttributeError):
"""Exception thrown when a detailed property is unavailable.
A search query from the places API returns only a summary of the Place.
in order to get full details, a further API call must be made using
the place_id. This exception will be thrown when a property made
available by only the detailed API call is looked up against the summary
object.
An explicit call to get_details() must be made on the summary object in
order to convert a summary object to a detailed object.
"""
# I could spend forever muling between this design decision and creating
# a PlaceSummary object as well as a Place object. I'm leaning towards this
# method in order to keep the API as simple as possible.
pass
class GooglePlaces(object):
"""A wrapper around the Google Places Query API."""
BASE_URL = 'https://maps.googleapis.com/maps/api'
PLACE_URL = BASE_URL + '/place'
GEOCODE_API_URL = BASE_URL + '/geocode/json?'
RADAR_SEARCH_API_URL = PLACE_URL + '/radarsearch/json?'
NEARBY_SEARCH_API_URL = PLACE_URL + '/nearbysearch/json?'
TEXT_SEARCH_API_URL = PLACE_URL + '/textsearch/json?'
AUTOCOMPLETE_API_URL = PLACE_URL + '/autocomplete/json?'
DETAIL_API_URL = PLACE_URL + '/details/json?'
CHECKIN_API_URL = PLACE_URL + '/check-in/json?sensor=%s&key=%s'
ADD_API_URL = PLACE_URL + '/add/json?sensor=%s&key=%s'
DELETE_API_URL = PLACE_URL + '/delete/json?sensor=%s&key=%s'
PHOTO_API_URL = PLACE_URL + '/photo?'
MAXIMUM_SEARCH_RADIUS = 50000
RESPONSE_STATUS_OK = 'OK'
RESPONSE_STATUS_ZERO_RESULTS = 'ZERO_RESULTS'
def __init__(self, api_key):
self._api_key = api_key
self._sensor = False
self._request_params = None
def query(self, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter('always')
warnings.warn('The query API is deprecated. Please use nearby_search.',
DeprecationWarning, stacklevel=2)
return self.nearby_search(**kwargs)
def nearby_search(self, language=lang.ENGLISH, keyword=None, location=None,
lat_lng=None, name=None, radius=3200, rankby=ranking.PROMINENCE,
sensor=False, type=None, types=[], pagetoken=None):
"""Perform a nearby search using the Google Places API.
One of either location, lat_lng or pagetoken are required, the rest of
the keyword arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
location -- A human readable location, e.g 'London, England'
(default None)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
name -- A term to be matched against the names of the Places.
Results will be restricted to those containing the passed
name value. (default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
rankby -- Specifies the order in which results are listed :
ranking.PROMINENCE (default) or ranking.DISTANCE
(imply no radius argument).
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
"""
if location is None and lat_lng is None and pagetoken is None:
raise ValueError('One of location, lat_lng or pagetoken must be passed in.')
if rankby == 'distance':
# As per API docs rankby == distance:
# One or more of keyword, name, or types is required.
if keyword is None and types == [] and name is None:
raise ValueError('When rankby = googleplaces.ranking.DISTANCE, ' +
'name, keyword or types kwargs ' +
'must be specified.')
self._sensor = sensor
radius = (radius if radius <= GooglePlaces.MAXIMUM_SEARCH_RADIUS
else GooglePlaces.MAXIMUM_SEARCH_RADIUS)
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params = {'location': lat_lng_str}
if rankby == 'prominence':
self._request_params['radius'] = radius
else:
self._request_params['rankby'] = rankby
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.NEARBY_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def text_search(self, query=None, language=lang.ENGLISH, lat_lng=None,
radius=3200, type=None, types=[], location=None, pagetoken=None):
"""Perform a text search using the Google Places API.
Only the one of the query or pagetoken kwargs are required, the rest of the
keyword arguments are optional.
keyword arguments:
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
query -- The text string on which to search, for example:
"Restaurant in New York".
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
"""
self._request_params = {'query': query}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.TEXT_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def autocomplete(self, input, lat_lng=None, location=None, radius=3200,
language=lang.ENGLISH, types=None, components=[]):
"""
Perform an autocomplete search using the Google Places API.
Only the input kwarg is required, the rest of the keyword arguments
are optional.
keyword arguments:
input -- The text string on which to search, for example:
"Hattie B's".
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location to which the
search is to be restricted. The maximum is 50000 meters.
(default 3200)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
types -- A type to search against. See `types.py` "autocomplete types"
for complete list
https://developers.google.com/places/documentation/autocomplete#place_types.
components -- An optional grouping of places to which you would
like to restrict your results. An array containing one or
more tuples of:
* country: matches a country name or a two letter ISO 3166-1 country code.
eg: [('country','US')]
"""
self._request_params = {'input': input}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if types:
self._request_params['types'] = types
if len(components) > 0:
self._request_params['components'] = '|'.join(['{}:{}'.format(
c[0],c[1]) for c in components])
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.AUTOCOMPLETE_API_URL, self._request_params)
_validate_response(url, places_response)
return GoogleAutocompleteSearchResult(self, places_response)
def radar_search(self, sensor=False, keyword=None, name=None,
language=lang.ENGLISH, lat_lng=None, opennow=False,
radius=3200, type=None, types=[], location=None):
"""Perform a radar search using the Google Places API.
One of lat_lng or location are required, the rest of the keyword
arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
name -- A term to be matched against the names of Places. Results will
be restricted to those containing the passed name value.
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
opennow -- Returns only those Places that are open for business at the time
the query is sent. (default False)
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param
"""
if keyword is None and name is None and len(types) is 0:
raise ValueError('One of keyword, name or types must be supplied.')
if location is None and lat_lng is None:
raise ValueError('One of location or lat_lng must be passed in.')
try:
radius = int(radius)
except:
raise ValueError('radius must be passed supplied as an integer.')
if sensor not in [True, False]:
raise ValueError('sensor must be passed in as a boolean value.')
self._request_params = {'radius': radius}
self._sensor = sensor
self._request_params['location'] = self._generate_lat_lng_string(
lat_lng, location)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if opennow is True:
self._request_params['opennow'] = 'true'
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.RADAR_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def checkin(self, place_id, sensor=False):
"""Checks in a user to a place.
keyword arguments:
place_id -- The unique Google identifier for the relevant place.
sensor -- Boolean flag denoting if the location came from a
device using its location sensor (default False).
"""
data = {'placeid': place_id}
url, checkin_response = _fetch_remote_json(
GooglePlaces.CHECKIN_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(data), use_http_post=True)
_validate_response(url, checkin_response)
def get_place(self, place_id, sensor=False, language=lang.ENGLISH):
"""Gets a detailed place object.
keyword arguments:
place_id -- The unique Google identifier for the required place.
sensor -- Boolean flag denoting if the location came from a
device using its' location sensor (default False).
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
"""
place_details = _get_place_details(place_id,
self.api_key, sensor, language=language)
return Place(self, place_details)
def add_place(self, **kwargs):
"""Adds a place to the Google Places database.
On a successful request, this method will return a dict containing
the the new Place's place_id and id in keys 'place_id' and 'id'
respectively.
keyword arguments:
name -- The full text name of the Place. Limited to 255
characters.
lat_lng -- A dict containing the following keys: lat, lng.
accuracy -- The accuracy of the location signal on which this request
is based, expressed in meters.
types -- The category in which this Place belongs. Only one type
can currently be specified for a Place. A string or
single element list may be passed in.
language -- The language in which the Place's name is being reported.
(defaults 'en').
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
required_kwargs = {'name': [str], 'lat_lng': [dict],
'accuracy': [int], 'types': [str, list]}
request_params = {}
for key in required_kwargs:
if key not in kwargs or kwargs[key] is None:
raise ValueError('The %s argument is required.' % key)
expected_types = required_kwargs[key]
type_is_valid = False
for expected_type in expected_types:
if isinstance(kwargs[key], expected_type):
type_is_valid = True
break
if not type_is_valid:
raise ValueError('Invalid value for %s' % key)
if key is not 'lat_lng':
request_params[key] = kwargs[key]
if len(kwargs['name']) > 255:
raise ValueError('The place name must not exceed 255 characters ' +
'in length.')
try:
kwargs['lat_lng']['lat']
kwargs['lat_lng']['lng']
request_params['location'] = kwargs['lat_lng']
except KeyError:
raise ValueError('Invalid keys for lat_lng.')
request_params['language'] = (kwargs.get('language')
if kwargs.get('language') is not None else
lang.ENGLISH)
sensor = (kwargs.get('sensor')
if kwargs.get('sensor') is not None else
False)
# At some point Google might support multiple types, so this supports
# strings and lists.
if isinstance(kwargs['types'], str):
request_params['types'] = [kwargs['types']]
else:
request_params['types'] = kwargs['types']
url, add_response = _fetch_remote_json(
GooglePlaces.ADD_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, add_response)
return {'place_id': add_response['place_id'],
'id': add_response['id']}
def delete_place(self, place_id, sensor=False):
"""Deletes a place from the Google Places database.
keyword arguments:
place_id -- The textual identifier that uniquely identifies this
Place, returned from a Place Search request.
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
request_params = {'place_id': place_id}
url, delete_response = _fetch_remote_json(
GooglePlaces.DELETE_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, delete_response)
def _add_required_param_keys(self):
self._request_params['key'] = self.api_key
self._request_params['sensor'] = str(self.sensor).lower()
def _generate_lat_lng_string(self, lat_lng, location):
try:
return '%(lat)s,%(lng)s' % (lat_lng if lat_lng is not None
else geocode_location(location=location, api_key=self.api_key))
except GooglePlacesError as e:
raise ValueError(
'lat_lng must be a dict with the keys, \'lat\' and \'lng\'. Cause: %s' % str(e))
@property
def request_params(self):
return self._request_params
@property
def api_key(self):
return self._api_key
@property
def sensor(self):
return self._sensor
class GoogleAutocompleteSearchResult(object):
"""Wrapper around the Google Autocomplete API query JSON response."""
def __init__(self, query_instance, response):
self._response = response
self._predictions = []
for prediction in response['predictions']:
self._predictions.append(Prediction(query_instance, prediction))
@property
def raw_response(self):
"""Returns the raw JSON response returned by the Autocomplete API."""
return self._response
@property
def predictions(self):
return self._predictions
def __repr__(self):
"""Return a string representation stating number of predictions."""
return '<{} with {} prediction(s)>'.format(
self.__class__.__name__,
len(self.predictions)
)
class Prediction(object):
"""
Represents a prediction from the results of a Google Places Autocomplete API query.
"""
def __init__(self, query_instance, prediction):
self._query_instance = query_instance
self._description = prediction['description']
self._id = prediction['id']
self._matched_substrings = prediction['matched_substrings']
self._place_id = prediction['place_id']
self._reference = prediction['reference']
self._terms = prediction['terms']
self._types = prediction.get('types',[])
if prediction.get('_description') is None:
self._place = None
else:
self._place = prediction
@property
def description(self):
"""
String representation of a Prediction location. Generally contains
name, country, and elements contained in the terms property.
"""
return self._description
@property
def id(self):
"""
Returns the deprecated id property.
This identifier may not be used to retrieve information about this
place, but is guaranteed to be valid across sessions. It can be used
to consolidate data about this Place, and to verify the identity of a
Place across separate searches.
This property is deprecated:
https://developers.google.com/places/documentation/autocomplete#deprecation
"""
return self._id
@property
def matched_substrings(self):
"""
Returns the placement and offset of the matched strings for this search.
A an array of dicts, each with the keys 'length' and 'offset', will be returned.
"""
return self._matched_substrings
@property
def place_id(self):
"""
Returns the unique stable identifier denoting this place.
This identifier may be used to retrieve information about this
place.
This should be considered the primary identifier of a place.
"""
return self._place_id
@property
def reference(self):
"""
Returns the deprecated reference property.
The token can be used to retrieve additional information about this
place when invoking the getPlace method on an GooglePlaces instance.
You can store this token and use it at any time in future to refresh
cached data about this Place, but the same token is not guaranteed to
be returned for any given Place across different searches.
This property is deprecated:
https://developers.google.com/places/documentation/autocomplete#deprecation
"""
return self._reference
@property
def terms(self):
"""
A list of terms which build up the description string
A an array of dicts, each with the keys `offset` and `value`, will be returned.
"""
return self._terms
@property
def types(self):
"""
Returns a list of feature types describing the given result.
"""
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types
# The following properties require a further API call in order to be
# available.
@property
def place(self):
"""
Returns the JSON response from Google Places Detail search API.
"""
self._validate_status()
return self._place
def get_details(self, language=None):
"""
Retrieves full information on the place matching the place_id.
Stores the response in the `place` property.
"""
if self._place is None:
if language is None:
try:
language = self._query_instance._request_params['language']
except KeyError:
language = lang.ENGLISH
place = _get_place_details(
self.place_id, self._query_instance.api_key,
self._query_instance.sensor, language=language)
self._place = Place(self._query_instance, place)
def _validate_status(self):
"""
Indicates specific properties are only available after a details call.
"""
if self._place is None:
error_detail = ('The attribute requested is only available after ' +
'an explicit call to get_details() is made.')
raise GooglePlacesAttributeError(error_detail)
def __repr__(self):
""" Return a string representation with description. """
return '<{} description="{}">'.format(self.__class__.__name__, self.description)
class GooglePlacesSearchResult(object):
"""
Wrapper around the Google Places API query JSON response.
"""
def __init__(self, query_instance, response):
self._response = response
self._places = []
for place in response['results']:
self._places.append(Place(query_instance, place))
self._html_attributions = response.get('html_attributions', [])
self._next_page_token = response.get('next_page_token', [])
@property
def raw_response(self):
"""
Returns the raw JSON response returned by the Places API.
"""
return self._response
@property
def places(self):
return self._places
@property
def html_attributions(self):
"""Returns the HTML attributions for the specified response.
Any returned HTML attributions MUST be displayed as-is, in accordance
with the requirements as found in the documentation. Please see the
module comments for links to the relevant url.
"""
return self._html_attributions
@property
def next_page_token(self):
"""Returns the next page token(next_page_token)."""
return self._next_page_token
@property
def has_attributions(self):
"""Returns a flag denoting if the response had any html attributions."""
return len(self.html_attributions) > 0
@property
def has_next_page_token(self):
"""Returns a flag denoting if the response had a next page token."""
return len(self.next_page_token) > 0
def __repr__(self):
""" Return a string representation stating the number of results."""
return '<{} with {} result(s)>'.format(self.__class__.__name__, len(self.places))
class Place(object):
"""
Represents a place from the results of a Google Places API query.
"""
def __init__(self, query_instance, place_data):
self._query_instance = query_instance
self._place_id = place_data['place_id']
self._id = place_data.get('id', '')
self._reference = place_data.get('reference', '')
self._name = place_data.get('name','')
self._vicinity = place_data.get('vicinity', '')
self._geo_location = place_data['geometry']['location']
self._rating = place_data.get('rating','')
self._types = place_data.get('types','')
self._icon = place_data.get('icon','')
if place_data.get('address_components') is None:
self._details = None
else:
self._details = place_data
@property
def reference(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns contains a unique token for the place.
The token can be used to retrieve additional information about this
place when invoking the getPlace method on an GooglePlaces instance.
You can store this token and use it at any time in future to refresh
cached data about this Place, but the same token is not guaranteed to
be returned for any given Place across different searches."""
warnings.warn('The "reference" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._reference
@property
def id(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns the unique stable identifier denoting this place.
This identifier may not be used to retrieve information about this
place, but is guaranteed to be valid across sessions. It can be used
to consolidate data about this Place, and to verify the identity of a
Place across separate searches.
"""
warnings.warn('The "id" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._id
@property
def place_id(self):
"""Returns the unique stable identifier denoting this place.
This identifier may be used to retrieve information about this
place.
This should be considered the primary identifier of a place.
"""
return self._place_id
@property
def icon(self):
"""Returns the URL of a recommended icon for display."""
if self._icon == '' and self.details != None and 'icon' in self.details:
self._icon = self.details['icon']
return self._icon
@property
def types(self):
"""Returns a list of feature types describing the given result."""
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types
@property
def geo_location(self):
"""Returns the lat lng co-ordinates of the place.
A dict with the keys 'lat' and 'lng' will be returned.
"""
return self._geo_location
@property
def name(self):
"""Returns the human-readable name of the place."""
if self._name == '' and self.details != None and 'name' in self.details:
self._name = self.details['name']
return self._name
@property
def vicinity(self):
"""Returns a feature name of a nearby location.
Often this feature refers to a street or neighborhood within the given
results.
"""
if self._vicinity == '' and self.details != None and 'vicinity' in self.details:
self._vicinity = self.details['vicinity']
return self._vicinity
@property
def rating(self):
"""Returns the Place's rating, from 0.0 to 5.0, based on user reviews.
This method will return None for places that have no rating.
"""
if self._rating == '' and self.details != None and 'rating' in self.details:
self._rating = self.details['rating']
return self._rating
# The following properties require a further API call in order to be
# available.
@property
def details(self):
"""Returns the JSON response from Google Places Detail search API."""
self._validate_status()
return self._details
@property
def formatted_address(self):
"""Returns a string containing the human-readable address of this place.
Often this address is equivalent to the "postal address," which
sometimes differs from country to country. (Note that some countries,
such as the United Kingdom, do not allow distribution of complete postal
addresses due to licensing restrictions.)
"""
self._validate_status()
return self.details.get('formatted_address')
@property
def local_phone_number(self):
"""Returns the Place's phone number in its local format."""
self._validate_status()
return self.details.get('formatted_phone_number')
@property
def international_phone_number(self):
self._validate_status()
return self.details.get('international_phone_number')
@property
def website(self):
"""Returns the authoritative website for this Place."""
self._validate_status()
return self.details.get('website')
@property
def url(self):
"""Contains the official Google Place Page URL of this establishment.
Applications must link to or embed the Google Place page on any screen
that shows detailed results about this Place to the user.
"""
self._validate_status()
return self.details.get('url')
@property
def html_attributions(self):
"""Returns the HTML attributions for the specified response.
Any returned HTML attributions MUST be displayed as-is, in accordance
with the requirements as found in the documentation. Please see the
module comments for links to the relevant url.
"""
self._validate_status()
return self.details.get('html_attributions', [])
@property
def has_attributions(self):
"""Returns a flag denoting if the response had any html attributions."""
return (False if self._details is None else
len(self.html_attributions) > 0)
def checkin(self):
"""Checks in an anonymous user in."""
self._query_instance.checkin(self.place_id,
self._query_instance.sensor)
def get_details(self, language=None):
"""Retrieves full information on the place matching the place_id.
Further attributes will be made available on the instance once this
method has been invoked.
keyword arguments:
language -- The language code, indicating in which language the
results should be returned, if possible. This value defaults
to the language that was used to generate the
GooglePlacesSearchResult instance.
"""
if self._details is None:
if language is None:
try:
language = self._query_instance._request_params['language']
except KeyError:
language = lang.ENGLISH
self._details = _get_place_details(
self.place_id, self._query_instance.api_key,
self._query_instance.sensor, language=language)
@cached_property
def photos(self):
self.get_details()
return [Photo(self._query_instance, i)
for i in self.details.get('photos', [])]
def _validate_status(self):
if self._details is None:
error_detail = ('The attribute requested is only available after ' +
'an explicit call to get_details() is made.')
raise GooglePlacesAttributeError(error_detail)
def __repr__(self):
""" Return a string representation including the name, lat, and lng. """
return '<{} name="{}", lat={}, lng={}>'.format(
self.__class__.__name__,
self.name,
self.geo_location['lat'],
self.geo_location['lng']
)
class Photo(object):
def __init__(self, query_instance, attrs):
self._query_instance = query_instance
self.orig_height = attrs.get('height')
self.orig_width = attrs.get('width')
self.html_attributions = attrs.get('html_attributions')
self.photo_reference = attrs.get('photo_reference')
def get(self, maxheight=None, maxwidth=None, sensor=False):
"""Fetch photo from API."""
if not maxheight and not maxwidth:
raise GooglePlacesError('You must specify maxheight or maxwidth!')
result = _get_place_photo(self.photo_reference,
self._query_instance.api_key,
maxheight=maxheight, maxwidth=maxwidth,
sensor=sensor)
self.mimetype, self.filename, self.data, self.url = result
|
slimkrazy/python-google-places | googleplaces/__init__.py | _validate_response | python | def _validate_response(url, response):
if response['status'] not in [GooglePlaces.RESPONSE_STATUS_OK,
GooglePlaces.RESPONSE_STATUS_ZERO_RESULTS]:
error_detail = ('Request to URL %s failed with response code: %s' %
(url, response['status']))
raise GooglePlacesError(error_detail) | Validates that the response from Google was successful. | train | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L169-L175 | null | """
A simple wrapper around the 'experimental' Google Places API, documented
here: http://code.google.com/apis/maps/documentation/places/. This library
also makes use of the v3 Maps API for geocoding.
Prerequisites: A Google API key with Places activated against it. Please
check the Google API console, here: http://code.google.com/apis/console
NOTE: Please ensure that you read the Google terms of service (labelled 'Limits
and Requirements' on the documentation url) prior to using this library in a
production environment.
@author: sam@slimkrazy.com
"""
from __future__ import absolute_import
import cgi
from decimal import Decimal
try:
import json
except ImportError:
import simplejson as json
try:
import six
from six.moves import urllib
except ImportError:
pass
import warnings
from . import lang
from . import ranking
__all__ = ['GooglePlaces', 'GooglePlacesError', 'GooglePlacesAttributeError',
'geocode_location']
__version__ = '1.4.1'
__author__ = 'Samuel Adu'
__email__ = 'sam@slimkrazy.com'
class cached_property(object):
def __init__(self, func):
self.func = func
def __get__(self, instance, cls=None):
result = instance.__dict__[self.func.__name__] = self.func(instance)
return result
def _fetch_remote(service_url, params=None, use_http_post=False):
if not params:
params = {}
encoded_data = {}
for k, v in params.items():
if isinstance(v, six.string_types):
v = v.encode('utf-8')
encoded_data[k] = v
encoded_data = urllib.parse.urlencode(encoded_data)
if not use_http_post:
query_url = (service_url if service_url.endswith('?') else
'%s?' % service_url)
request_url = query_url + encoded_data
request = urllib.request.Request(request_url)
else:
request_url = service_url
request = urllib.request.Request(service_url, data=encoded_data)
return (request_url, urllib.request.urlopen(request))
def _fetch_remote_json(service_url, params=None, use_http_post=False):
"""Retrieves a JSON object from a URL."""
if not params:
params = {}
request_url, response = _fetch_remote(service_url, params, use_http_post)
if six.PY3:
str_response = response.read().decode('utf-8')
return (request_url, json.loads(str_response, parse_float=Decimal))
return (request_url, json.load(response, parse_float=Decimal))
def _fetch_remote_file(service_url, params=None, use_http_post=False):
"""Retrieves a file from a URL.
Returns a tuple (mimetype, filename, data)
"""
if not params:
params = {}
request_url, response = _fetch_remote(service_url, params, use_http_post)
dummy, params = cgi.parse_header(
response.headers.get('Content-Disposition', ''))
fn = params['filename']
return (response.headers.get('content-type'),
fn, response.read(), response.geturl())
def geocode_location(location, sensor=False, api_key=None):
"""Converts a human-readable location to lat-lng.
Returns a dict with lat and lng keys.
keyword arguments:
location -- A human-readable location, e.g 'London, England'
sensor -- Boolean flag denoting if the location came from a device using
its' location sensor (default False)
api_key -- A valid Google Places API key.
raises:
GooglePlacesError -- if the geocoder fails to find a location.
"""
params = {'address': location, 'sensor': str(sensor).lower()}
if api_key is not None:
params['key'] = api_key
url, geo_response = _fetch_remote_json(
GooglePlaces.GEOCODE_API_URL, params)
_validate_response(url, geo_response)
if geo_response['status'] == GooglePlaces.RESPONSE_STATUS_ZERO_RESULTS:
error_detail = ('Lat/Lng for location \'%s\' can\'t be determined.' %
location)
raise GooglePlacesError(error_detail)
return geo_response['results'][0]['geometry']['location']
def _get_place_details(place_id, api_key, sensor=False,
language=lang.ENGLISH):
"""Gets a detailed place response.
keyword arguments:
place_id -- The unique identifier for the required place.
"""
url, detail_response = _fetch_remote_json(GooglePlaces.DETAIL_API_URL,
{'placeid': place_id,
'sensor': str(sensor).lower(),
'key': api_key,
'language': language})
_validate_response(url, detail_response)
return detail_response['result']
def _get_place_photo(photoreference, api_key, maxheight=None, maxwidth=None,
sensor=False):
"""Gets a place's photo by reference.
See detailed documentation at https://developers.google.com/places/documentation/photos
Arguments:
photoreference -- The unique Google reference for the required photo.
Keyword arguments:
maxheight -- The maximum desired photo height in pixels
maxwidth -- The maximum desired photo width in pixels
You must specify one of this keyword arguments. Acceptable value is an
integer between 1 and 1600.
"""
params = {'photoreference': photoreference,
'sensor': str(sensor).lower(),
'key': api_key}
if maxheight:
params['maxheight'] = maxheight
if maxwidth:
params['maxwidth'] = maxwidth
return _fetch_remote_file(GooglePlaces.PHOTO_API_URL, params)
class GooglePlacesError(Exception):
pass
class GooglePlacesAttributeError(AttributeError):
"""Exception thrown when a detailed property is unavailable.
A search query from the places API returns only a summary of the Place.
in order to get full details, a further API call must be made using
the place_id. This exception will be thrown when a property made
available by only the detailed API call is looked up against the summary
object.
An explicit call to get_details() must be made on the summary object in
order to convert a summary object to a detailed object.
"""
# I could spend forever muling between this design decision and creating
# a PlaceSummary object as well as a Place object. I'm leaning towards this
# method in order to keep the API as simple as possible.
pass
class GooglePlaces(object):
"""A wrapper around the Google Places Query API."""
BASE_URL = 'https://maps.googleapis.com/maps/api'
PLACE_URL = BASE_URL + '/place'
GEOCODE_API_URL = BASE_URL + '/geocode/json?'
RADAR_SEARCH_API_URL = PLACE_URL + '/radarsearch/json?'
NEARBY_SEARCH_API_URL = PLACE_URL + '/nearbysearch/json?'
TEXT_SEARCH_API_URL = PLACE_URL + '/textsearch/json?'
AUTOCOMPLETE_API_URL = PLACE_URL + '/autocomplete/json?'
DETAIL_API_URL = PLACE_URL + '/details/json?'
CHECKIN_API_URL = PLACE_URL + '/check-in/json?sensor=%s&key=%s'
ADD_API_URL = PLACE_URL + '/add/json?sensor=%s&key=%s'
DELETE_API_URL = PLACE_URL + '/delete/json?sensor=%s&key=%s'
PHOTO_API_URL = PLACE_URL + '/photo?'
MAXIMUM_SEARCH_RADIUS = 50000
RESPONSE_STATUS_OK = 'OK'
RESPONSE_STATUS_ZERO_RESULTS = 'ZERO_RESULTS'
def __init__(self, api_key):
self._api_key = api_key
self._sensor = False
self._request_params = None
def query(self, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter('always')
warnings.warn('The query API is deprecated. Please use nearby_search.',
DeprecationWarning, stacklevel=2)
return self.nearby_search(**kwargs)
def nearby_search(self, language=lang.ENGLISH, keyword=None, location=None,
lat_lng=None, name=None, radius=3200, rankby=ranking.PROMINENCE,
sensor=False, type=None, types=[], pagetoken=None):
"""Perform a nearby search using the Google Places API.
One of either location, lat_lng or pagetoken are required, the rest of
the keyword arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
location -- A human readable location, e.g 'London, England'
(default None)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
name -- A term to be matched against the names of the Places.
Results will be restricted to those containing the passed
name value. (default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
rankby -- Specifies the order in which results are listed :
ranking.PROMINENCE (default) or ranking.DISTANCE
(imply no radius argument).
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
"""
if location is None and lat_lng is None and pagetoken is None:
raise ValueError('One of location, lat_lng or pagetoken must be passed in.')
if rankby == 'distance':
# As per API docs rankby == distance:
# One or more of keyword, name, or types is required.
if keyword is None and types == [] and name is None:
raise ValueError('When rankby = googleplaces.ranking.DISTANCE, ' +
'name, keyword or types kwargs ' +
'must be specified.')
self._sensor = sensor
radius = (radius if radius <= GooglePlaces.MAXIMUM_SEARCH_RADIUS
else GooglePlaces.MAXIMUM_SEARCH_RADIUS)
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params = {'location': lat_lng_str}
if rankby == 'prominence':
self._request_params['radius'] = radius
else:
self._request_params['rankby'] = rankby
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.NEARBY_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def text_search(self, query=None, language=lang.ENGLISH, lat_lng=None,
radius=3200, type=None, types=[], location=None, pagetoken=None):
"""Perform a text search using the Google Places API.
Only the one of the query or pagetoken kwargs are required, the rest of the
keyword arguments are optional.
keyword arguments:
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
query -- The text string on which to search, for example:
"Restaurant in New York".
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
"""
self._request_params = {'query': query}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.TEXT_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def autocomplete(self, input, lat_lng=None, location=None, radius=3200,
language=lang.ENGLISH, types=None, components=[]):
"""
Perform an autocomplete search using the Google Places API.
Only the input kwarg is required, the rest of the keyword arguments
are optional.
keyword arguments:
input -- The text string on which to search, for example:
"Hattie B's".
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location to which the
search is to be restricted. The maximum is 50000 meters.
(default 3200)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
types -- A type to search against. See `types.py` "autocomplete types"
for complete list
https://developers.google.com/places/documentation/autocomplete#place_types.
components -- An optional grouping of places to which you would
like to restrict your results. An array containing one or
more tuples of:
* country: matches a country name or a two letter ISO 3166-1 country code.
eg: [('country','US')]
"""
self._request_params = {'input': input}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if types:
self._request_params['types'] = types
if len(components) > 0:
self._request_params['components'] = '|'.join(['{}:{}'.format(
c[0],c[1]) for c in components])
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.AUTOCOMPLETE_API_URL, self._request_params)
_validate_response(url, places_response)
return GoogleAutocompleteSearchResult(self, places_response)
def radar_search(self, sensor=False, keyword=None, name=None,
language=lang.ENGLISH, lat_lng=None, opennow=False,
radius=3200, type=None, types=[], location=None):
"""Perform a radar search using the Google Places API.
One of lat_lng or location are required, the rest of the keyword
arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
name -- A term to be matched against the names of Places. Results will
be restricted to those containing the passed name value.
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
opennow -- Returns only those Places that are open for business at the time
the query is sent. (default False)
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param
"""
if keyword is None and name is None and len(types) is 0:
raise ValueError('One of keyword, name or types must be supplied.')
if location is None and lat_lng is None:
raise ValueError('One of location or lat_lng must be passed in.')
try:
radius = int(radius)
except:
raise ValueError('radius must be passed supplied as an integer.')
if sensor not in [True, False]:
raise ValueError('sensor must be passed in as a boolean value.')
self._request_params = {'radius': radius}
self._sensor = sensor
self._request_params['location'] = self._generate_lat_lng_string(
lat_lng, location)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if opennow is True:
self._request_params['opennow'] = 'true'
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.RADAR_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def checkin(self, place_id, sensor=False):
"""Checks in a user to a place.
keyword arguments:
place_id -- The unique Google identifier for the relevant place.
sensor -- Boolean flag denoting if the location came from a
device using its location sensor (default False).
"""
data = {'placeid': place_id}
url, checkin_response = _fetch_remote_json(
GooglePlaces.CHECKIN_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(data), use_http_post=True)
_validate_response(url, checkin_response)
def get_place(self, place_id, sensor=False, language=lang.ENGLISH):
"""Gets a detailed place object.
keyword arguments:
place_id -- The unique Google identifier for the required place.
sensor -- Boolean flag denoting if the location came from a
device using its' location sensor (default False).
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
"""
place_details = _get_place_details(place_id,
self.api_key, sensor, language=language)
return Place(self, place_details)
def add_place(self, **kwargs):
"""Adds a place to the Google Places database.
On a successful request, this method will return a dict containing
the the new Place's place_id and id in keys 'place_id' and 'id'
respectively.
keyword arguments:
name -- The full text name of the Place. Limited to 255
characters.
lat_lng -- A dict containing the following keys: lat, lng.
accuracy -- The accuracy of the location signal on which this request
is based, expressed in meters.
types -- The category in which this Place belongs. Only one type
can currently be specified for a Place. A string or
single element list may be passed in.
language -- The language in which the Place's name is being reported.
(defaults 'en').
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
required_kwargs = {'name': [str], 'lat_lng': [dict],
'accuracy': [int], 'types': [str, list]}
request_params = {}
for key in required_kwargs:
if key not in kwargs or kwargs[key] is None:
raise ValueError('The %s argument is required.' % key)
expected_types = required_kwargs[key]
type_is_valid = False
for expected_type in expected_types:
if isinstance(kwargs[key], expected_type):
type_is_valid = True
break
if not type_is_valid:
raise ValueError('Invalid value for %s' % key)
if key is not 'lat_lng':
request_params[key] = kwargs[key]
if len(kwargs['name']) > 255:
raise ValueError('The place name must not exceed 255 characters ' +
'in length.')
try:
kwargs['lat_lng']['lat']
kwargs['lat_lng']['lng']
request_params['location'] = kwargs['lat_lng']
except KeyError:
raise ValueError('Invalid keys for lat_lng.')
request_params['language'] = (kwargs.get('language')
if kwargs.get('language') is not None else
lang.ENGLISH)
sensor = (kwargs.get('sensor')
if kwargs.get('sensor') is not None else
False)
# At some point Google might support multiple types, so this supports
# strings and lists.
if isinstance(kwargs['types'], str):
request_params['types'] = [kwargs['types']]
else:
request_params['types'] = kwargs['types']
url, add_response = _fetch_remote_json(
GooglePlaces.ADD_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, add_response)
return {'place_id': add_response['place_id'],
'id': add_response['id']}
def delete_place(self, place_id, sensor=False):
"""Deletes a place from the Google Places database.
keyword arguments:
place_id -- The textual identifier that uniquely identifies this
Place, returned from a Place Search request.
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
request_params = {'place_id': place_id}
url, delete_response = _fetch_remote_json(
GooglePlaces.DELETE_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, delete_response)
def _add_required_param_keys(self):
self._request_params['key'] = self.api_key
self._request_params['sensor'] = str(self.sensor).lower()
def _generate_lat_lng_string(self, lat_lng, location):
try:
return '%(lat)s,%(lng)s' % (lat_lng if lat_lng is not None
else geocode_location(location=location, api_key=self.api_key))
except GooglePlacesError as e:
raise ValueError(
'lat_lng must be a dict with the keys, \'lat\' and \'lng\'. Cause: %s' % str(e))
@property
def request_params(self):
return self._request_params
@property
def api_key(self):
return self._api_key
@property
def sensor(self):
return self._sensor
class GoogleAutocompleteSearchResult(object):
"""Wrapper around the Google Autocomplete API query JSON response."""
def __init__(self, query_instance, response):
self._response = response
self._predictions = []
for prediction in response['predictions']:
self._predictions.append(Prediction(query_instance, prediction))
@property
def raw_response(self):
"""Returns the raw JSON response returned by the Autocomplete API."""
return self._response
@property
def predictions(self):
return self._predictions
def __repr__(self):
"""Return a string representation stating number of predictions."""
return '<{} with {} prediction(s)>'.format(
self.__class__.__name__,
len(self.predictions)
)
class Prediction(object):
"""
Represents a prediction from the results of a Google Places Autocomplete API query.
"""
def __init__(self, query_instance, prediction):
self._query_instance = query_instance
self._description = prediction['description']
self._id = prediction['id']
self._matched_substrings = prediction['matched_substrings']
self._place_id = prediction['place_id']
self._reference = prediction['reference']
self._terms = prediction['terms']
self._types = prediction.get('types',[])
if prediction.get('_description') is None:
self._place = None
else:
self._place = prediction
@property
def description(self):
"""
String representation of a Prediction location. Generally contains
name, country, and elements contained in the terms property.
"""
return self._description
@property
def id(self):
"""
Returns the deprecated id property.
This identifier may not be used to retrieve information about this
place, but is guaranteed to be valid across sessions. It can be used
to consolidate data about this Place, and to verify the identity of a
Place across separate searches.
This property is deprecated:
https://developers.google.com/places/documentation/autocomplete#deprecation
"""
return self._id
@property
def matched_substrings(self):
"""
Returns the placement and offset of the matched strings for this search.
A an array of dicts, each with the keys 'length' and 'offset', will be returned.
"""
return self._matched_substrings
@property
def place_id(self):
"""
Returns the unique stable identifier denoting this place.
This identifier may be used to retrieve information about this
place.
This should be considered the primary identifier of a place.
"""
return self._place_id
@property
def reference(self):
"""
Returns the deprecated reference property.
The token can be used to retrieve additional information about this
place when invoking the getPlace method on an GooglePlaces instance.
You can store this token and use it at any time in future to refresh
cached data about this Place, but the same token is not guaranteed to
be returned for any given Place across different searches.
This property is deprecated:
https://developers.google.com/places/documentation/autocomplete#deprecation
"""
return self._reference
@property
def terms(self):
"""
A list of terms which build up the description string
A an array of dicts, each with the keys `offset` and `value`, will be returned.
"""
return self._terms
@property
def types(self):
"""
Returns a list of feature types describing the given result.
"""
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types
# The following properties require a further API call in order to be
# available.
@property
def place(self):
"""
Returns the JSON response from Google Places Detail search API.
"""
self._validate_status()
return self._place
def get_details(self, language=None):
"""
Retrieves full information on the place matching the place_id.
Stores the response in the `place` property.
"""
if self._place is None:
if language is None:
try:
language = self._query_instance._request_params['language']
except KeyError:
language = lang.ENGLISH
place = _get_place_details(
self.place_id, self._query_instance.api_key,
self._query_instance.sensor, language=language)
self._place = Place(self._query_instance, place)
def _validate_status(self):
"""
Indicates specific properties are only available after a details call.
"""
if self._place is None:
error_detail = ('The attribute requested is only available after ' +
'an explicit call to get_details() is made.')
raise GooglePlacesAttributeError(error_detail)
def __repr__(self):
""" Return a string representation with description. """
return '<{} description="{}">'.format(self.__class__.__name__, self.description)
class GooglePlacesSearchResult(object):
"""
Wrapper around the Google Places API query JSON response.
"""
def __init__(self, query_instance, response):
self._response = response
self._places = []
for place in response['results']:
self._places.append(Place(query_instance, place))
self._html_attributions = response.get('html_attributions', [])
self._next_page_token = response.get('next_page_token', [])
@property
def raw_response(self):
"""
Returns the raw JSON response returned by the Places API.
"""
return self._response
@property
def places(self):
return self._places
@property
def html_attributions(self):
"""Returns the HTML attributions for the specified response.
Any returned HTML attributions MUST be displayed as-is, in accordance
with the requirements as found in the documentation. Please see the
module comments for links to the relevant url.
"""
return self._html_attributions
@property
def next_page_token(self):
"""Returns the next page token(next_page_token)."""
return self._next_page_token
@property
def has_attributions(self):
"""Returns a flag denoting if the response had any html attributions."""
return len(self.html_attributions) > 0
@property
def has_next_page_token(self):
"""Returns a flag denoting if the response had a next page token."""
return len(self.next_page_token) > 0
def __repr__(self):
""" Return a string representation stating the number of results."""
return '<{} with {} result(s)>'.format(self.__class__.__name__, len(self.places))
class Place(object):
"""
Represents a place from the results of a Google Places API query.
"""
def __init__(self, query_instance, place_data):
self._query_instance = query_instance
self._place_id = place_data['place_id']
self._id = place_data.get('id', '')
self._reference = place_data.get('reference', '')
self._name = place_data.get('name','')
self._vicinity = place_data.get('vicinity', '')
self._geo_location = place_data['geometry']['location']
self._rating = place_data.get('rating','')
self._types = place_data.get('types','')
self._icon = place_data.get('icon','')
if place_data.get('address_components') is None:
self._details = None
else:
self._details = place_data
@property
def reference(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns contains a unique token for the place.
The token can be used to retrieve additional information about this
place when invoking the getPlace method on an GooglePlaces instance.
You can store this token and use it at any time in future to refresh
cached data about this Place, but the same token is not guaranteed to
be returned for any given Place across different searches."""
warnings.warn('The "reference" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._reference
@property
def id(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns the unique stable identifier denoting this place.
This identifier may not be used to retrieve information about this
place, but is guaranteed to be valid across sessions. It can be used
to consolidate data about this Place, and to verify the identity of a
Place across separate searches.
"""
warnings.warn('The "id" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._id
@property
def place_id(self):
"""Returns the unique stable identifier denoting this place.
This identifier may be used to retrieve information about this
place.
This should be considered the primary identifier of a place.
"""
return self._place_id
@property
def icon(self):
"""Returns the URL of a recommended icon for display."""
if self._icon == '' and self.details != None and 'icon' in self.details:
self._icon = self.details['icon']
return self._icon
@property
def types(self):
"""Returns a list of feature types describing the given result."""
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types
@property
def geo_location(self):
"""Returns the lat lng co-ordinates of the place.
A dict with the keys 'lat' and 'lng' will be returned.
"""
return self._geo_location
@property
def name(self):
"""Returns the human-readable name of the place."""
if self._name == '' and self.details != None and 'name' in self.details:
self._name = self.details['name']
return self._name
@property
def vicinity(self):
"""Returns a feature name of a nearby location.
Often this feature refers to a street or neighborhood within the given
results.
"""
if self._vicinity == '' and self.details != None and 'vicinity' in self.details:
self._vicinity = self.details['vicinity']
return self._vicinity
@property
def rating(self):
"""Returns the Place's rating, from 0.0 to 5.0, based on user reviews.
This method will return None for places that have no rating.
"""
if self._rating == '' and self.details != None and 'rating' in self.details:
self._rating = self.details['rating']
return self._rating
# The following properties require a further API call in order to be
# available.
@property
def details(self):
"""Returns the JSON response from Google Places Detail search API."""
self._validate_status()
return self._details
@property
def formatted_address(self):
"""Returns a string containing the human-readable address of this place.
Often this address is equivalent to the "postal address," which
sometimes differs from country to country. (Note that some countries,
such as the United Kingdom, do not allow distribution of complete postal
addresses due to licensing restrictions.)
"""
self._validate_status()
return self.details.get('formatted_address')
@property
def local_phone_number(self):
"""Returns the Place's phone number in its local format."""
self._validate_status()
return self.details.get('formatted_phone_number')
@property
def international_phone_number(self):
self._validate_status()
return self.details.get('international_phone_number')
@property
def website(self):
"""Returns the authoritative website for this Place."""
self._validate_status()
return self.details.get('website')
@property
def url(self):
"""Contains the official Google Place Page URL of this establishment.
Applications must link to or embed the Google Place page on any screen
that shows detailed results about this Place to the user.
"""
self._validate_status()
return self.details.get('url')
@property
def html_attributions(self):
"""Returns the HTML attributions for the specified response.
Any returned HTML attributions MUST be displayed as-is, in accordance
with the requirements as found in the documentation. Please see the
module comments for links to the relevant url.
"""
self._validate_status()
return self.details.get('html_attributions', [])
@property
def has_attributions(self):
"""Returns a flag denoting if the response had any html attributions."""
return (False if self._details is None else
len(self.html_attributions) > 0)
def checkin(self):
"""Checks in an anonymous user in."""
self._query_instance.checkin(self.place_id,
self._query_instance.sensor)
def get_details(self, language=None):
"""Retrieves full information on the place matching the place_id.
Further attributes will be made available on the instance once this
method has been invoked.
keyword arguments:
language -- The language code, indicating in which language the
results should be returned, if possible. This value defaults
to the language that was used to generate the
GooglePlacesSearchResult instance.
"""
if self._details is None:
if language is None:
try:
language = self._query_instance._request_params['language']
except KeyError:
language = lang.ENGLISH
self._details = _get_place_details(
self.place_id, self._query_instance.api_key,
self._query_instance.sensor, language=language)
@cached_property
def photos(self):
self.get_details()
return [Photo(self._query_instance, i)
for i in self.details.get('photos', [])]
def _validate_status(self):
if self._details is None:
error_detail = ('The attribute requested is only available after ' +
'an explicit call to get_details() is made.')
raise GooglePlacesAttributeError(error_detail)
def __repr__(self):
""" Return a string representation including the name, lat, and lng. """
return '<{} name="{}", lat={}, lng={}>'.format(
self.__class__.__name__,
self.name,
self.geo_location['lat'],
self.geo_location['lng']
)
class Photo(object):
def __init__(self, query_instance, attrs):
self._query_instance = query_instance
self.orig_height = attrs.get('height')
self.orig_width = attrs.get('width')
self.html_attributions = attrs.get('html_attributions')
self.photo_reference = attrs.get('photo_reference')
def get(self, maxheight=None, maxwidth=None, sensor=False):
"""Fetch photo from API."""
if not maxheight and not maxwidth:
raise GooglePlacesError('You must specify maxheight or maxwidth!')
result = _get_place_photo(self.photo_reference,
self._query_instance.api_key,
maxheight=maxheight, maxwidth=maxwidth,
sensor=sensor)
self.mimetype, self.filename, self.data, self.url = result
|
slimkrazy/python-google-places | googleplaces/__init__.py | GooglePlaces.nearby_search | python | def nearby_search(self, language=lang.ENGLISH, keyword=None, location=None,
lat_lng=None, name=None, radius=3200, rankby=ranking.PROMINENCE,
sensor=False, type=None, types=[], pagetoken=None):
if location is None and lat_lng is None and pagetoken is None:
raise ValueError('One of location, lat_lng or pagetoken must be passed in.')
if rankby == 'distance':
# As per API docs rankby == distance:
# One or more of keyword, name, or types is required.
if keyword is None and types == [] and name is None:
raise ValueError('When rankby = googleplaces.ranking.DISTANCE, ' +
'name, keyword or types kwargs ' +
'must be specified.')
self._sensor = sensor
radius = (radius if radius <= GooglePlaces.MAXIMUM_SEARCH_RADIUS
else GooglePlaces.MAXIMUM_SEARCH_RADIUS)
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params = {'location': lat_lng_str}
if rankby == 'prominence':
self._request_params['radius'] = radius
else:
self._request_params['rankby'] = rankby
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.NEARBY_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response) | Perform a nearby search using the Google Places API.
One of either location, lat_lng or pagetoken are required, the rest of
the keyword arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
location -- A human readable location, e.g 'London, England'
(default None)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
name -- A term to be matched against the names of the Places.
Results will be restricted to those containing the passed
name value. (default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
rankby -- Specifies the order in which results are listed :
ranking.PROMINENCE (default) or ranking.DISTANCE
(imply no radius argument).
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None) | train | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L232-L306 | [
"def _fetch_remote_json(service_url, params=None, use_http_post=False):\n \"\"\"Retrieves a JSON object from a URL.\"\"\"\n if not params:\n params = {}\n\n request_url, response = _fetch_remote(service_url, params, use_http_post)\n if six.PY3:\n str_response = response.read().decode('utf-... | class GooglePlaces(object):
"""A wrapper around the Google Places Query API."""
BASE_URL = 'https://maps.googleapis.com/maps/api'
PLACE_URL = BASE_URL + '/place'
GEOCODE_API_URL = BASE_URL + '/geocode/json?'
RADAR_SEARCH_API_URL = PLACE_URL + '/radarsearch/json?'
NEARBY_SEARCH_API_URL = PLACE_URL + '/nearbysearch/json?'
TEXT_SEARCH_API_URL = PLACE_URL + '/textsearch/json?'
AUTOCOMPLETE_API_URL = PLACE_URL + '/autocomplete/json?'
DETAIL_API_URL = PLACE_URL + '/details/json?'
CHECKIN_API_URL = PLACE_URL + '/check-in/json?sensor=%s&key=%s'
ADD_API_URL = PLACE_URL + '/add/json?sensor=%s&key=%s'
DELETE_API_URL = PLACE_URL + '/delete/json?sensor=%s&key=%s'
PHOTO_API_URL = PLACE_URL + '/photo?'
MAXIMUM_SEARCH_RADIUS = 50000
RESPONSE_STATUS_OK = 'OK'
RESPONSE_STATUS_ZERO_RESULTS = 'ZERO_RESULTS'
def __init__(self, api_key):
self._api_key = api_key
self._sensor = False
self._request_params = None
def query(self, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter('always')
warnings.warn('The query API is deprecated. Please use nearby_search.',
DeprecationWarning, stacklevel=2)
return self.nearby_search(**kwargs)
def text_search(self, query=None, language=lang.ENGLISH, lat_lng=None,
radius=3200, type=None, types=[], location=None, pagetoken=None):
"""Perform a text search using the Google Places API.
Only the one of the query or pagetoken kwargs are required, the rest of the
keyword arguments are optional.
keyword arguments:
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
query -- The text string on which to search, for example:
"Restaurant in New York".
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
"""
self._request_params = {'query': query}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.TEXT_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def autocomplete(self, input, lat_lng=None, location=None, radius=3200,
language=lang.ENGLISH, types=None, components=[]):
"""
Perform an autocomplete search using the Google Places API.
Only the input kwarg is required, the rest of the keyword arguments
are optional.
keyword arguments:
input -- The text string on which to search, for example:
"Hattie B's".
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location to which the
search is to be restricted. The maximum is 50000 meters.
(default 3200)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
types -- A type to search against. See `types.py` "autocomplete types"
for complete list
https://developers.google.com/places/documentation/autocomplete#place_types.
components -- An optional grouping of places to which you would
like to restrict your results. An array containing one or
more tuples of:
* country: matches a country name or a two letter ISO 3166-1 country code.
eg: [('country','US')]
"""
self._request_params = {'input': input}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if types:
self._request_params['types'] = types
if len(components) > 0:
self._request_params['components'] = '|'.join(['{}:{}'.format(
c[0],c[1]) for c in components])
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.AUTOCOMPLETE_API_URL, self._request_params)
_validate_response(url, places_response)
return GoogleAutocompleteSearchResult(self, places_response)
def radar_search(self, sensor=False, keyword=None, name=None,
language=lang.ENGLISH, lat_lng=None, opennow=False,
radius=3200, type=None, types=[], location=None):
"""Perform a radar search using the Google Places API.
One of lat_lng or location are required, the rest of the keyword
arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
name -- A term to be matched against the names of Places. Results will
be restricted to those containing the passed name value.
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
opennow -- Returns only those Places that are open for business at the time
the query is sent. (default False)
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param
"""
if keyword is None and name is None and len(types) is 0:
raise ValueError('One of keyword, name or types must be supplied.')
if location is None and lat_lng is None:
raise ValueError('One of location or lat_lng must be passed in.')
try:
radius = int(radius)
except:
raise ValueError('radius must be passed supplied as an integer.')
if sensor not in [True, False]:
raise ValueError('sensor must be passed in as a boolean value.')
self._request_params = {'radius': radius}
self._sensor = sensor
self._request_params['location'] = self._generate_lat_lng_string(
lat_lng, location)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if opennow is True:
self._request_params['opennow'] = 'true'
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.RADAR_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def checkin(self, place_id, sensor=False):
"""Checks in a user to a place.
keyword arguments:
place_id -- The unique Google identifier for the relevant place.
sensor -- Boolean flag denoting if the location came from a
device using its location sensor (default False).
"""
data = {'placeid': place_id}
url, checkin_response = _fetch_remote_json(
GooglePlaces.CHECKIN_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(data), use_http_post=True)
_validate_response(url, checkin_response)
def get_place(self, place_id, sensor=False, language=lang.ENGLISH):
"""Gets a detailed place object.
keyword arguments:
place_id -- The unique Google identifier for the required place.
sensor -- Boolean flag denoting if the location came from a
device using its' location sensor (default False).
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
"""
place_details = _get_place_details(place_id,
self.api_key, sensor, language=language)
return Place(self, place_details)
def add_place(self, **kwargs):
"""Adds a place to the Google Places database.
On a successful request, this method will return a dict containing
the the new Place's place_id and id in keys 'place_id' and 'id'
respectively.
keyword arguments:
name -- The full text name of the Place. Limited to 255
characters.
lat_lng -- A dict containing the following keys: lat, lng.
accuracy -- The accuracy of the location signal on which this request
is based, expressed in meters.
types -- The category in which this Place belongs. Only one type
can currently be specified for a Place. A string or
single element list may be passed in.
language -- The language in which the Place's name is being reported.
(defaults 'en').
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
required_kwargs = {'name': [str], 'lat_lng': [dict],
'accuracy': [int], 'types': [str, list]}
request_params = {}
for key in required_kwargs:
if key not in kwargs or kwargs[key] is None:
raise ValueError('The %s argument is required.' % key)
expected_types = required_kwargs[key]
type_is_valid = False
for expected_type in expected_types:
if isinstance(kwargs[key], expected_type):
type_is_valid = True
break
if not type_is_valid:
raise ValueError('Invalid value for %s' % key)
if key is not 'lat_lng':
request_params[key] = kwargs[key]
if len(kwargs['name']) > 255:
raise ValueError('The place name must not exceed 255 characters ' +
'in length.')
try:
kwargs['lat_lng']['lat']
kwargs['lat_lng']['lng']
request_params['location'] = kwargs['lat_lng']
except KeyError:
raise ValueError('Invalid keys for lat_lng.')
request_params['language'] = (kwargs.get('language')
if kwargs.get('language') is not None else
lang.ENGLISH)
sensor = (kwargs.get('sensor')
if kwargs.get('sensor') is not None else
False)
# At some point Google might support multiple types, so this supports
# strings and lists.
if isinstance(kwargs['types'], str):
request_params['types'] = [kwargs['types']]
else:
request_params['types'] = kwargs['types']
url, add_response = _fetch_remote_json(
GooglePlaces.ADD_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, add_response)
return {'place_id': add_response['place_id'],
'id': add_response['id']}
def delete_place(self, place_id, sensor=False):
"""Deletes a place from the Google Places database.
keyword arguments:
place_id -- The textual identifier that uniquely identifies this
Place, returned from a Place Search request.
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
request_params = {'place_id': place_id}
url, delete_response = _fetch_remote_json(
GooglePlaces.DELETE_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, delete_response)
def _add_required_param_keys(self):
self._request_params['key'] = self.api_key
self._request_params['sensor'] = str(self.sensor).lower()
def _generate_lat_lng_string(self, lat_lng, location):
try:
return '%(lat)s,%(lng)s' % (lat_lng if lat_lng is not None
else geocode_location(location=location, api_key=self.api_key))
except GooglePlacesError as e:
raise ValueError(
'lat_lng must be a dict with the keys, \'lat\' and \'lng\'. Cause: %s' % str(e))
@property
def request_params(self):
return self._request_params
@property
def api_key(self):
return self._api_key
@property
def sensor(self):
return self._sensor
|
slimkrazy/python-google-places | googleplaces/__init__.py | GooglePlaces.text_search | python | def text_search(self, query=None, language=lang.ENGLISH, lat_lng=None,
radius=3200, type=None, types=[], location=None, pagetoken=None):
self._request_params = {'query': query}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.TEXT_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response) | Perform a text search using the Google Places API.
Only the one of the query or pagetoken kwargs are required, the rest of the
keyword arguments are optional.
keyword arguments:
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
query -- The text string on which to search, for example:
"Restaurant in New York".
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param. | train | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L308-L354 | [
"def _fetch_remote_json(service_url, params=None, use_http_post=False):\n \"\"\"Retrieves a JSON object from a URL.\"\"\"\n if not params:\n params = {}\n\n request_url, response = _fetch_remote(service_url, params, use_http_post)\n if six.PY3:\n str_response = response.read().decode('utf-... | class GooglePlaces(object):
"""A wrapper around the Google Places Query API."""
BASE_URL = 'https://maps.googleapis.com/maps/api'
PLACE_URL = BASE_URL + '/place'
GEOCODE_API_URL = BASE_URL + '/geocode/json?'
RADAR_SEARCH_API_URL = PLACE_URL + '/radarsearch/json?'
NEARBY_SEARCH_API_URL = PLACE_URL + '/nearbysearch/json?'
TEXT_SEARCH_API_URL = PLACE_URL + '/textsearch/json?'
AUTOCOMPLETE_API_URL = PLACE_URL + '/autocomplete/json?'
DETAIL_API_URL = PLACE_URL + '/details/json?'
CHECKIN_API_URL = PLACE_URL + '/check-in/json?sensor=%s&key=%s'
ADD_API_URL = PLACE_URL + '/add/json?sensor=%s&key=%s'
DELETE_API_URL = PLACE_URL + '/delete/json?sensor=%s&key=%s'
PHOTO_API_URL = PLACE_URL + '/photo?'
MAXIMUM_SEARCH_RADIUS = 50000
RESPONSE_STATUS_OK = 'OK'
RESPONSE_STATUS_ZERO_RESULTS = 'ZERO_RESULTS'
def __init__(self, api_key):
self._api_key = api_key
self._sensor = False
self._request_params = None
def query(self, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter('always')
warnings.warn('The query API is deprecated. Please use nearby_search.',
DeprecationWarning, stacklevel=2)
return self.nearby_search(**kwargs)
def nearby_search(self, language=lang.ENGLISH, keyword=None, location=None,
lat_lng=None, name=None, radius=3200, rankby=ranking.PROMINENCE,
sensor=False, type=None, types=[], pagetoken=None):
"""Perform a nearby search using the Google Places API.
One of either location, lat_lng or pagetoken are required, the rest of
the keyword arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
location -- A human readable location, e.g 'London, England'
(default None)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
name -- A term to be matched against the names of the Places.
Results will be restricted to those containing the passed
name value. (default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
rankby -- Specifies the order in which results are listed :
ranking.PROMINENCE (default) or ranking.DISTANCE
(imply no radius argument).
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
"""
if location is None and lat_lng is None and pagetoken is None:
raise ValueError('One of location, lat_lng or pagetoken must be passed in.')
if rankby == 'distance':
# As per API docs rankby == distance:
# One or more of keyword, name, or types is required.
if keyword is None and types == [] and name is None:
raise ValueError('When rankby = googleplaces.ranking.DISTANCE, ' +
'name, keyword or types kwargs ' +
'must be specified.')
self._sensor = sensor
radius = (radius if radius <= GooglePlaces.MAXIMUM_SEARCH_RADIUS
else GooglePlaces.MAXIMUM_SEARCH_RADIUS)
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params = {'location': lat_lng_str}
if rankby == 'prominence':
self._request_params['radius'] = radius
else:
self._request_params['rankby'] = rankby
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.NEARBY_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def autocomplete(self, input, lat_lng=None, location=None, radius=3200,
language=lang.ENGLISH, types=None, components=[]):
"""
Perform an autocomplete search using the Google Places API.
Only the input kwarg is required, the rest of the keyword arguments
are optional.
keyword arguments:
input -- The text string on which to search, for example:
"Hattie B's".
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location to which the
search is to be restricted. The maximum is 50000 meters.
(default 3200)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
types -- A type to search against. See `types.py` "autocomplete types"
for complete list
https://developers.google.com/places/documentation/autocomplete#place_types.
components -- An optional grouping of places to which you would
like to restrict your results. An array containing one or
more tuples of:
* country: matches a country name or a two letter ISO 3166-1 country code.
eg: [('country','US')]
"""
self._request_params = {'input': input}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if types:
self._request_params['types'] = types
if len(components) > 0:
self._request_params['components'] = '|'.join(['{}:{}'.format(
c[0],c[1]) for c in components])
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.AUTOCOMPLETE_API_URL, self._request_params)
_validate_response(url, places_response)
return GoogleAutocompleteSearchResult(self, places_response)
def radar_search(self, sensor=False, keyword=None, name=None,
language=lang.ENGLISH, lat_lng=None, opennow=False,
radius=3200, type=None, types=[], location=None):
"""Perform a radar search using the Google Places API.
One of lat_lng or location are required, the rest of the keyword
arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
name -- A term to be matched against the names of Places. Results will
be restricted to those containing the passed name value.
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
opennow -- Returns only those Places that are open for business at the time
the query is sent. (default False)
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param
"""
if keyword is None and name is None and len(types) is 0:
raise ValueError('One of keyword, name or types must be supplied.')
if location is None and lat_lng is None:
raise ValueError('One of location or lat_lng must be passed in.')
try:
radius = int(radius)
except:
raise ValueError('radius must be passed supplied as an integer.')
if sensor not in [True, False]:
raise ValueError('sensor must be passed in as a boolean value.')
self._request_params = {'radius': radius}
self._sensor = sensor
self._request_params['location'] = self._generate_lat_lng_string(
lat_lng, location)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if opennow is True:
self._request_params['opennow'] = 'true'
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.RADAR_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def checkin(self, place_id, sensor=False):
"""Checks in a user to a place.
keyword arguments:
place_id -- The unique Google identifier for the relevant place.
sensor -- Boolean flag denoting if the location came from a
device using its location sensor (default False).
"""
data = {'placeid': place_id}
url, checkin_response = _fetch_remote_json(
GooglePlaces.CHECKIN_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(data), use_http_post=True)
_validate_response(url, checkin_response)
def get_place(self, place_id, sensor=False, language=lang.ENGLISH):
"""Gets a detailed place object.
keyword arguments:
place_id -- The unique Google identifier for the required place.
sensor -- Boolean flag denoting if the location came from a
device using its' location sensor (default False).
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
"""
place_details = _get_place_details(place_id,
self.api_key, sensor, language=language)
return Place(self, place_details)
def add_place(self, **kwargs):
"""Adds a place to the Google Places database.
On a successful request, this method will return a dict containing
the the new Place's place_id and id in keys 'place_id' and 'id'
respectively.
keyword arguments:
name -- The full text name of the Place. Limited to 255
characters.
lat_lng -- A dict containing the following keys: lat, lng.
accuracy -- The accuracy of the location signal on which this request
is based, expressed in meters.
types -- The category in which this Place belongs. Only one type
can currently be specified for a Place. A string or
single element list may be passed in.
language -- The language in which the Place's name is being reported.
(defaults 'en').
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
required_kwargs = {'name': [str], 'lat_lng': [dict],
'accuracy': [int], 'types': [str, list]}
request_params = {}
for key in required_kwargs:
if key not in kwargs or kwargs[key] is None:
raise ValueError('The %s argument is required.' % key)
expected_types = required_kwargs[key]
type_is_valid = False
for expected_type in expected_types:
if isinstance(kwargs[key], expected_type):
type_is_valid = True
break
if not type_is_valid:
raise ValueError('Invalid value for %s' % key)
if key is not 'lat_lng':
request_params[key] = kwargs[key]
if len(kwargs['name']) > 255:
raise ValueError('The place name must not exceed 255 characters ' +
'in length.')
try:
kwargs['lat_lng']['lat']
kwargs['lat_lng']['lng']
request_params['location'] = kwargs['lat_lng']
except KeyError:
raise ValueError('Invalid keys for lat_lng.')
request_params['language'] = (kwargs.get('language')
if kwargs.get('language') is not None else
lang.ENGLISH)
sensor = (kwargs.get('sensor')
if kwargs.get('sensor') is not None else
False)
# At some point Google might support multiple types, so this supports
# strings and lists.
if isinstance(kwargs['types'], str):
request_params['types'] = [kwargs['types']]
else:
request_params['types'] = kwargs['types']
url, add_response = _fetch_remote_json(
GooglePlaces.ADD_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, add_response)
return {'place_id': add_response['place_id'],
'id': add_response['id']}
def delete_place(self, place_id, sensor=False):
"""Deletes a place from the Google Places database.
keyword arguments:
place_id -- The textual identifier that uniquely identifies this
Place, returned from a Place Search request.
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
request_params = {'place_id': place_id}
url, delete_response = _fetch_remote_json(
GooglePlaces.DELETE_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, delete_response)
def _add_required_param_keys(self):
self._request_params['key'] = self.api_key
self._request_params['sensor'] = str(self.sensor).lower()
def _generate_lat_lng_string(self, lat_lng, location):
try:
return '%(lat)s,%(lng)s' % (lat_lng if lat_lng is not None
else geocode_location(location=location, api_key=self.api_key))
except GooglePlacesError as e:
raise ValueError(
'lat_lng must be a dict with the keys, \'lat\' and \'lng\'. Cause: %s' % str(e))
@property
def request_params(self):
return self._request_params
@property
def api_key(self):
return self._api_key
@property
def sensor(self):
return self._sensor
|
slimkrazy/python-google-places | googleplaces/__init__.py | GooglePlaces.autocomplete | python | def autocomplete(self, input, lat_lng=None, location=None, radius=3200,
language=lang.ENGLISH, types=None, components=[]):
self._request_params = {'input': input}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if types:
self._request_params['types'] = types
if len(components) > 0:
self._request_params['components'] = '|'.join(['{}:{}'.format(
c[0],c[1]) for c in components])
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.AUTOCOMPLETE_API_URL, self._request_params)
_validate_response(url, places_response)
return GoogleAutocompleteSearchResult(self, places_response) | Perform an autocomplete search using the Google Places API.
Only the input kwarg is required, the rest of the keyword arguments
are optional.
keyword arguments:
input -- The text string on which to search, for example:
"Hattie B's".
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location to which the
search is to be restricted. The maximum is 50000 meters.
(default 3200)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
types -- A type to search against. See `types.py` "autocomplete types"
for complete list
https://developers.google.com/places/documentation/autocomplete#place_types.
components -- An optional grouping of places to which you would
like to restrict your results. An array containing one or
more tuples of:
* country: matches a country name or a two letter ISO 3166-1 country code.
eg: [('country','US')] | train | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L356-L401 | [
"def _fetch_remote_json(service_url, params=None, use_http_post=False):\n \"\"\"Retrieves a JSON object from a URL.\"\"\"\n if not params:\n params = {}\n\n request_url, response = _fetch_remote(service_url, params, use_http_post)\n if six.PY3:\n str_response = response.read().decode('utf-... | class GooglePlaces(object):
"""A wrapper around the Google Places Query API."""
BASE_URL = 'https://maps.googleapis.com/maps/api'
PLACE_URL = BASE_URL + '/place'
GEOCODE_API_URL = BASE_URL + '/geocode/json?'
RADAR_SEARCH_API_URL = PLACE_URL + '/radarsearch/json?'
NEARBY_SEARCH_API_URL = PLACE_URL + '/nearbysearch/json?'
TEXT_SEARCH_API_URL = PLACE_URL + '/textsearch/json?'
AUTOCOMPLETE_API_URL = PLACE_URL + '/autocomplete/json?'
DETAIL_API_URL = PLACE_URL + '/details/json?'
CHECKIN_API_URL = PLACE_URL + '/check-in/json?sensor=%s&key=%s'
ADD_API_URL = PLACE_URL + '/add/json?sensor=%s&key=%s'
DELETE_API_URL = PLACE_URL + '/delete/json?sensor=%s&key=%s'
PHOTO_API_URL = PLACE_URL + '/photo?'
MAXIMUM_SEARCH_RADIUS = 50000
RESPONSE_STATUS_OK = 'OK'
RESPONSE_STATUS_ZERO_RESULTS = 'ZERO_RESULTS'
def __init__(self, api_key):
self._api_key = api_key
self._sensor = False
self._request_params = None
def query(self, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter('always')
warnings.warn('The query API is deprecated. Please use nearby_search.',
DeprecationWarning, stacklevel=2)
return self.nearby_search(**kwargs)
def nearby_search(self, language=lang.ENGLISH, keyword=None, location=None,
lat_lng=None, name=None, radius=3200, rankby=ranking.PROMINENCE,
sensor=False, type=None, types=[], pagetoken=None):
"""Perform a nearby search using the Google Places API.
One of either location, lat_lng or pagetoken are required, the rest of
the keyword arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
location -- A human readable location, e.g 'London, England'
(default None)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
name -- A term to be matched against the names of the Places.
Results will be restricted to those containing the passed
name value. (default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
rankby -- Specifies the order in which results are listed :
ranking.PROMINENCE (default) or ranking.DISTANCE
(imply no radius argument).
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
"""
if location is None and lat_lng is None and pagetoken is None:
raise ValueError('One of location, lat_lng or pagetoken must be passed in.')
if rankby == 'distance':
# As per API docs rankby == distance:
# One or more of keyword, name, or types is required.
if keyword is None and types == [] and name is None:
raise ValueError('When rankby = googleplaces.ranking.DISTANCE, ' +
'name, keyword or types kwargs ' +
'must be specified.')
self._sensor = sensor
radius = (radius if radius <= GooglePlaces.MAXIMUM_SEARCH_RADIUS
else GooglePlaces.MAXIMUM_SEARCH_RADIUS)
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params = {'location': lat_lng_str}
if rankby == 'prominence':
self._request_params['radius'] = radius
else:
self._request_params['rankby'] = rankby
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.NEARBY_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def text_search(self, query=None, language=lang.ENGLISH, lat_lng=None,
radius=3200, type=None, types=[], location=None, pagetoken=None):
"""Perform a text search using the Google Places API.
Only the one of the query or pagetoken kwargs are required, the rest of the
keyword arguments are optional.
keyword arguments:
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
query -- The text string on which to search, for example:
"Restaurant in New York".
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
"""
self._request_params = {'query': query}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.TEXT_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def radar_search(self, sensor=False, keyword=None, name=None,
language=lang.ENGLISH, lat_lng=None, opennow=False,
radius=3200, type=None, types=[], location=None):
"""Perform a radar search using the Google Places API.
One of lat_lng or location are required, the rest of the keyword
arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
name -- A term to be matched against the names of Places. Results will
be restricted to those containing the passed name value.
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
opennow -- Returns only those Places that are open for business at the time
the query is sent. (default False)
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param
"""
if keyword is None and name is None and len(types) is 0:
raise ValueError('One of keyword, name or types must be supplied.')
if location is None and lat_lng is None:
raise ValueError('One of location or lat_lng must be passed in.')
try:
radius = int(radius)
except:
raise ValueError('radius must be passed supplied as an integer.')
if sensor not in [True, False]:
raise ValueError('sensor must be passed in as a boolean value.')
self._request_params = {'radius': radius}
self._sensor = sensor
self._request_params['location'] = self._generate_lat_lng_string(
lat_lng, location)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if opennow is True:
self._request_params['opennow'] = 'true'
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.RADAR_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def checkin(self, place_id, sensor=False):
"""Checks in a user to a place.
keyword arguments:
place_id -- The unique Google identifier for the relevant place.
sensor -- Boolean flag denoting if the location came from a
device using its location sensor (default False).
"""
data = {'placeid': place_id}
url, checkin_response = _fetch_remote_json(
GooglePlaces.CHECKIN_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(data), use_http_post=True)
_validate_response(url, checkin_response)
def get_place(self, place_id, sensor=False, language=lang.ENGLISH):
"""Gets a detailed place object.
keyword arguments:
place_id -- The unique Google identifier for the required place.
sensor -- Boolean flag denoting if the location came from a
device using its' location sensor (default False).
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
"""
place_details = _get_place_details(place_id,
self.api_key, sensor, language=language)
return Place(self, place_details)
def add_place(self, **kwargs):
"""Adds a place to the Google Places database.
On a successful request, this method will return a dict containing
the the new Place's place_id and id in keys 'place_id' and 'id'
respectively.
keyword arguments:
name -- The full text name of the Place. Limited to 255
characters.
lat_lng -- A dict containing the following keys: lat, lng.
accuracy -- The accuracy of the location signal on which this request
is based, expressed in meters.
types -- The category in which this Place belongs. Only one type
can currently be specified for a Place. A string or
single element list may be passed in.
language -- The language in which the Place's name is being reported.
(defaults 'en').
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
required_kwargs = {'name': [str], 'lat_lng': [dict],
'accuracy': [int], 'types': [str, list]}
request_params = {}
for key in required_kwargs:
if key not in kwargs or kwargs[key] is None:
raise ValueError('The %s argument is required.' % key)
expected_types = required_kwargs[key]
type_is_valid = False
for expected_type in expected_types:
if isinstance(kwargs[key], expected_type):
type_is_valid = True
break
if not type_is_valid:
raise ValueError('Invalid value for %s' % key)
if key is not 'lat_lng':
request_params[key] = kwargs[key]
if len(kwargs['name']) > 255:
raise ValueError('The place name must not exceed 255 characters ' +
'in length.')
try:
kwargs['lat_lng']['lat']
kwargs['lat_lng']['lng']
request_params['location'] = kwargs['lat_lng']
except KeyError:
raise ValueError('Invalid keys for lat_lng.')
request_params['language'] = (kwargs.get('language')
if kwargs.get('language') is not None else
lang.ENGLISH)
sensor = (kwargs.get('sensor')
if kwargs.get('sensor') is not None else
False)
# At some point Google might support multiple types, so this supports
# strings and lists.
if isinstance(kwargs['types'], str):
request_params['types'] = [kwargs['types']]
else:
request_params['types'] = kwargs['types']
url, add_response = _fetch_remote_json(
GooglePlaces.ADD_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, add_response)
return {'place_id': add_response['place_id'],
'id': add_response['id']}
def delete_place(self, place_id, sensor=False):
"""Deletes a place from the Google Places database.
keyword arguments:
place_id -- The textual identifier that uniquely identifies this
Place, returned from a Place Search request.
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
request_params = {'place_id': place_id}
url, delete_response = _fetch_remote_json(
GooglePlaces.DELETE_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, delete_response)
def _add_required_param_keys(self):
self._request_params['key'] = self.api_key
self._request_params['sensor'] = str(self.sensor).lower()
def _generate_lat_lng_string(self, lat_lng, location):
try:
return '%(lat)s,%(lng)s' % (lat_lng if lat_lng is not None
else geocode_location(location=location, api_key=self.api_key))
except GooglePlacesError as e:
raise ValueError(
'lat_lng must be a dict with the keys, \'lat\' and \'lng\'. Cause: %s' % str(e))
@property
def request_params(self):
return self._request_params
@property
def api_key(self):
return self._api_key
@property
def sensor(self):
return self._sensor
|
slimkrazy/python-google-places | googleplaces/__init__.py | GooglePlaces.radar_search | python | def radar_search(self, sensor=False, keyword=None, name=None,
language=lang.ENGLISH, lat_lng=None, opennow=False,
radius=3200, type=None, types=[], location=None):
if keyword is None and name is None and len(types) is 0:
raise ValueError('One of keyword, name or types must be supplied.')
if location is None and lat_lng is None:
raise ValueError('One of location or lat_lng must be passed in.')
try:
radius = int(radius)
except:
raise ValueError('radius must be passed supplied as an integer.')
if sensor not in [True, False]:
raise ValueError('sensor must be passed in as a boolean value.')
self._request_params = {'radius': radius}
self._sensor = sensor
self._request_params['location'] = self._generate_lat_lng_string(
lat_lng, location)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if opennow is True:
self._request_params['opennow'] = 'true'
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.RADAR_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response) | Perform a radar search using the Google Places API.
One of lat_lng or location are required, the rest of the keyword
arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
name -- A term to be matched against the names of Places. Results will
be restricted to those containing the passed name value.
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
opennow -- Returns only those Places that are open for business at the time
the query is sent. (default False)
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param | train | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L403-L468 | [
"def _fetch_remote_json(service_url, params=None, use_http_post=False):\n \"\"\"Retrieves a JSON object from a URL.\"\"\"\n if not params:\n params = {}\n\n request_url, response = _fetch_remote(service_url, params, use_http_post)\n if six.PY3:\n str_response = response.read().decode('utf-... | class GooglePlaces(object):
"""A wrapper around the Google Places Query API."""
BASE_URL = 'https://maps.googleapis.com/maps/api'
PLACE_URL = BASE_URL + '/place'
GEOCODE_API_URL = BASE_URL + '/geocode/json?'
RADAR_SEARCH_API_URL = PLACE_URL + '/radarsearch/json?'
NEARBY_SEARCH_API_URL = PLACE_URL + '/nearbysearch/json?'
TEXT_SEARCH_API_URL = PLACE_URL + '/textsearch/json?'
AUTOCOMPLETE_API_URL = PLACE_URL + '/autocomplete/json?'
DETAIL_API_URL = PLACE_URL + '/details/json?'
CHECKIN_API_URL = PLACE_URL + '/check-in/json?sensor=%s&key=%s'
ADD_API_URL = PLACE_URL + '/add/json?sensor=%s&key=%s'
DELETE_API_URL = PLACE_URL + '/delete/json?sensor=%s&key=%s'
PHOTO_API_URL = PLACE_URL + '/photo?'
MAXIMUM_SEARCH_RADIUS = 50000
RESPONSE_STATUS_OK = 'OK'
RESPONSE_STATUS_ZERO_RESULTS = 'ZERO_RESULTS'
def __init__(self, api_key):
self._api_key = api_key
self._sensor = False
self._request_params = None
def query(self, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter('always')
warnings.warn('The query API is deprecated. Please use nearby_search.',
DeprecationWarning, stacklevel=2)
return self.nearby_search(**kwargs)
def nearby_search(self, language=lang.ENGLISH, keyword=None, location=None,
lat_lng=None, name=None, radius=3200, rankby=ranking.PROMINENCE,
sensor=False, type=None, types=[], pagetoken=None):
"""Perform a nearby search using the Google Places API.
One of either location, lat_lng or pagetoken are required, the rest of
the keyword arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
location -- A human readable location, e.g 'London, England'
(default None)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
name -- A term to be matched against the names of the Places.
Results will be restricted to those containing the passed
name value. (default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
rankby -- Specifies the order in which results are listed :
ranking.PROMINENCE (default) or ranking.DISTANCE
(imply no radius argument).
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
"""
if location is None and lat_lng is None and pagetoken is None:
raise ValueError('One of location, lat_lng or pagetoken must be passed in.')
if rankby == 'distance':
# As per API docs rankby == distance:
# One or more of keyword, name, or types is required.
if keyword is None and types == [] and name is None:
raise ValueError('When rankby = googleplaces.ranking.DISTANCE, ' +
'name, keyword or types kwargs ' +
'must be specified.')
self._sensor = sensor
radius = (radius if radius <= GooglePlaces.MAXIMUM_SEARCH_RADIUS
else GooglePlaces.MAXIMUM_SEARCH_RADIUS)
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params = {'location': lat_lng_str}
if rankby == 'prominence':
self._request_params['radius'] = radius
else:
self._request_params['rankby'] = rankby
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.NEARBY_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def text_search(self, query=None, language=lang.ENGLISH, lat_lng=None,
radius=3200, type=None, types=[], location=None, pagetoken=None):
"""Perform a text search using the Google Places API.
Only the one of the query or pagetoken kwargs are required, the rest of the
keyword arguments are optional.
keyword arguments:
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
query -- The text string on which to search, for example:
"Restaurant in New York".
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
"""
self._request_params = {'query': query}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.TEXT_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def autocomplete(self, input, lat_lng=None, location=None, radius=3200,
language=lang.ENGLISH, types=None, components=[]):
"""
Perform an autocomplete search using the Google Places API.
Only the input kwarg is required, the rest of the keyword arguments
are optional.
keyword arguments:
input -- The text string on which to search, for example:
"Hattie B's".
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location to which the
search is to be restricted. The maximum is 50000 meters.
(default 3200)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
types -- A type to search against. See `types.py` "autocomplete types"
for complete list
https://developers.google.com/places/documentation/autocomplete#place_types.
components -- An optional grouping of places to which you would
like to restrict your results. An array containing one or
more tuples of:
* country: matches a country name or a two letter ISO 3166-1 country code.
eg: [('country','US')]
"""
self._request_params = {'input': input}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if types:
self._request_params['types'] = types
if len(components) > 0:
self._request_params['components'] = '|'.join(['{}:{}'.format(
c[0],c[1]) for c in components])
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.AUTOCOMPLETE_API_URL, self._request_params)
_validate_response(url, places_response)
return GoogleAutocompleteSearchResult(self, places_response)
def checkin(self, place_id, sensor=False):
"""Checks in a user to a place.
keyword arguments:
place_id -- The unique Google identifier for the relevant place.
sensor -- Boolean flag denoting if the location came from a
device using its location sensor (default False).
"""
data = {'placeid': place_id}
url, checkin_response = _fetch_remote_json(
GooglePlaces.CHECKIN_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(data), use_http_post=True)
_validate_response(url, checkin_response)
def get_place(self, place_id, sensor=False, language=lang.ENGLISH):
"""Gets a detailed place object.
keyword arguments:
place_id -- The unique Google identifier for the required place.
sensor -- Boolean flag denoting if the location came from a
device using its' location sensor (default False).
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
"""
place_details = _get_place_details(place_id,
self.api_key, sensor, language=language)
return Place(self, place_details)
def add_place(self, **kwargs):
"""Adds a place to the Google Places database.
On a successful request, this method will return a dict containing
the the new Place's place_id and id in keys 'place_id' and 'id'
respectively.
keyword arguments:
name -- The full text name of the Place. Limited to 255
characters.
lat_lng -- A dict containing the following keys: lat, lng.
accuracy -- The accuracy of the location signal on which this request
is based, expressed in meters.
types -- The category in which this Place belongs. Only one type
can currently be specified for a Place. A string or
single element list may be passed in.
language -- The language in which the Place's name is being reported.
(defaults 'en').
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
required_kwargs = {'name': [str], 'lat_lng': [dict],
'accuracy': [int], 'types': [str, list]}
request_params = {}
for key in required_kwargs:
if key not in kwargs or kwargs[key] is None:
raise ValueError('The %s argument is required.' % key)
expected_types = required_kwargs[key]
type_is_valid = False
for expected_type in expected_types:
if isinstance(kwargs[key], expected_type):
type_is_valid = True
break
if not type_is_valid:
raise ValueError('Invalid value for %s' % key)
if key is not 'lat_lng':
request_params[key] = kwargs[key]
if len(kwargs['name']) > 255:
raise ValueError('The place name must not exceed 255 characters ' +
'in length.')
try:
kwargs['lat_lng']['lat']
kwargs['lat_lng']['lng']
request_params['location'] = kwargs['lat_lng']
except KeyError:
raise ValueError('Invalid keys for lat_lng.')
request_params['language'] = (kwargs.get('language')
if kwargs.get('language') is not None else
lang.ENGLISH)
sensor = (kwargs.get('sensor')
if kwargs.get('sensor') is not None else
False)
# At some point Google might support multiple types, so this supports
# strings and lists.
if isinstance(kwargs['types'], str):
request_params['types'] = [kwargs['types']]
else:
request_params['types'] = kwargs['types']
url, add_response = _fetch_remote_json(
GooglePlaces.ADD_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, add_response)
return {'place_id': add_response['place_id'],
'id': add_response['id']}
def delete_place(self, place_id, sensor=False):
"""Deletes a place from the Google Places database.
keyword arguments:
place_id -- The textual identifier that uniquely identifies this
Place, returned from a Place Search request.
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
request_params = {'place_id': place_id}
url, delete_response = _fetch_remote_json(
GooglePlaces.DELETE_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, delete_response)
def _add_required_param_keys(self):
self._request_params['key'] = self.api_key
self._request_params['sensor'] = str(self.sensor).lower()
def _generate_lat_lng_string(self, lat_lng, location):
try:
return '%(lat)s,%(lng)s' % (lat_lng if lat_lng is not None
else geocode_location(location=location, api_key=self.api_key))
except GooglePlacesError as e:
raise ValueError(
'lat_lng must be a dict with the keys, \'lat\' and \'lng\'. Cause: %s' % str(e))
@property
def request_params(self):
return self._request_params
@property
def api_key(self):
return self._api_key
@property
def sensor(self):
return self._sensor
|
slimkrazy/python-google-places | googleplaces/__init__.py | GooglePlaces.checkin | python | def checkin(self, place_id, sensor=False):
data = {'placeid': place_id}
url, checkin_response = _fetch_remote_json(
GooglePlaces.CHECKIN_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(data), use_http_post=True)
_validate_response(url, checkin_response) | Checks in a user to a place.
keyword arguments:
place_id -- The unique Google identifier for the relevant place.
sensor -- Boolean flag denoting if the location came from a
device using its location sensor (default False). | train | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L470-L482 | [
"def _fetch_remote_json(service_url, params=None, use_http_post=False):\n \"\"\"Retrieves a JSON object from a URL.\"\"\"\n if not params:\n params = {}\n\n request_url, response = _fetch_remote(service_url, params, use_http_post)\n if six.PY3:\n str_response = response.read().decode('utf-... | class GooglePlaces(object):
"""A wrapper around the Google Places Query API."""
BASE_URL = 'https://maps.googleapis.com/maps/api'
PLACE_URL = BASE_URL + '/place'
GEOCODE_API_URL = BASE_URL + '/geocode/json?'
RADAR_SEARCH_API_URL = PLACE_URL + '/radarsearch/json?'
NEARBY_SEARCH_API_URL = PLACE_URL + '/nearbysearch/json?'
TEXT_SEARCH_API_URL = PLACE_URL + '/textsearch/json?'
AUTOCOMPLETE_API_URL = PLACE_URL + '/autocomplete/json?'
DETAIL_API_URL = PLACE_URL + '/details/json?'
CHECKIN_API_URL = PLACE_URL + '/check-in/json?sensor=%s&key=%s'
ADD_API_URL = PLACE_URL + '/add/json?sensor=%s&key=%s'
DELETE_API_URL = PLACE_URL + '/delete/json?sensor=%s&key=%s'
PHOTO_API_URL = PLACE_URL + '/photo?'
MAXIMUM_SEARCH_RADIUS = 50000
RESPONSE_STATUS_OK = 'OK'
RESPONSE_STATUS_ZERO_RESULTS = 'ZERO_RESULTS'
def __init__(self, api_key):
self._api_key = api_key
self._sensor = False
self._request_params = None
def query(self, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter('always')
warnings.warn('The query API is deprecated. Please use nearby_search.',
DeprecationWarning, stacklevel=2)
return self.nearby_search(**kwargs)
def nearby_search(self, language=lang.ENGLISH, keyword=None, location=None,
lat_lng=None, name=None, radius=3200, rankby=ranking.PROMINENCE,
sensor=False, type=None, types=[], pagetoken=None):
"""Perform a nearby search using the Google Places API.
One of either location, lat_lng or pagetoken are required, the rest of
the keyword arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
location -- A human readable location, e.g 'London, England'
(default None)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
name -- A term to be matched against the names of the Places.
Results will be restricted to those containing the passed
name value. (default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
rankby -- Specifies the order in which results are listed :
ranking.PROMINENCE (default) or ranking.DISTANCE
(imply no radius argument).
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
"""
if location is None and lat_lng is None and pagetoken is None:
raise ValueError('One of location, lat_lng or pagetoken must be passed in.')
if rankby == 'distance':
# As per API docs rankby == distance:
# One or more of keyword, name, or types is required.
if keyword is None and types == [] and name is None:
raise ValueError('When rankby = googleplaces.ranking.DISTANCE, ' +
'name, keyword or types kwargs ' +
'must be specified.')
self._sensor = sensor
radius = (radius if radius <= GooglePlaces.MAXIMUM_SEARCH_RADIUS
else GooglePlaces.MAXIMUM_SEARCH_RADIUS)
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params = {'location': lat_lng_str}
if rankby == 'prominence':
self._request_params['radius'] = radius
else:
self._request_params['rankby'] = rankby
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.NEARBY_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def text_search(self, query=None, language=lang.ENGLISH, lat_lng=None,
radius=3200, type=None, types=[], location=None, pagetoken=None):
"""Perform a text search using the Google Places API.
Only the one of the query or pagetoken kwargs are required, the rest of the
keyword arguments are optional.
keyword arguments:
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
query -- The text string on which to search, for example:
"Restaurant in New York".
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
"""
self._request_params = {'query': query}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.TEXT_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def autocomplete(self, input, lat_lng=None, location=None, radius=3200,
language=lang.ENGLISH, types=None, components=[]):
"""
Perform an autocomplete search using the Google Places API.
Only the input kwarg is required, the rest of the keyword arguments
are optional.
keyword arguments:
input -- The text string on which to search, for example:
"Hattie B's".
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location to which the
search is to be restricted. The maximum is 50000 meters.
(default 3200)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
types -- A type to search against. See `types.py` "autocomplete types"
for complete list
https://developers.google.com/places/documentation/autocomplete#place_types.
components -- An optional grouping of places to which you would
like to restrict your results. An array containing one or
more tuples of:
* country: matches a country name or a two letter ISO 3166-1 country code.
eg: [('country','US')]
"""
self._request_params = {'input': input}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if types:
self._request_params['types'] = types
if len(components) > 0:
self._request_params['components'] = '|'.join(['{}:{}'.format(
c[0],c[1]) for c in components])
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.AUTOCOMPLETE_API_URL, self._request_params)
_validate_response(url, places_response)
return GoogleAutocompleteSearchResult(self, places_response)
def radar_search(self, sensor=False, keyword=None, name=None,
language=lang.ENGLISH, lat_lng=None, opennow=False,
radius=3200, type=None, types=[], location=None):
"""Perform a radar search using the Google Places API.
One of lat_lng or location are required, the rest of the keyword
arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
name -- A term to be matched against the names of Places. Results will
be restricted to those containing the passed name value.
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
opennow -- Returns only those Places that are open for business at the time
the query is sent. (default False)
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param
"""
if keyword is None and name is None and len(types) is 0:
raise ValueError('One of keyword, name or types must be supplied.')
if location is None and lat_lng is None:
raise ValueError('One of location or lat_lng must be passed in.')
try:
radius = int(radius)
except:
raise ValueError('radius must be passed supplied as an integer.')
if sensor not in [True, False]:
raise ValueError('sensor must be passed in as a boolean value.')
self._request_params = {'radius': radius}
self._sensor = sensor
self._request_params['location'] = self._generate_lat_lng_string(
lat_lng, location)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if opennow is True:
self._request_params['opennow'] = 'true'
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.RADAR_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def get_place(self, place_id, sensor=False, language=lang.ENGLISH):
"""Gets a detailed place object.
keyword arguments:
place_id -- The unique Google identifier for the required place.
sensor -- Boolean flag denoting if the location came from a
device using its' location sensor (default False).
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
"""
place_details = _get_place_details(place_id,
self.api_key, sensor, language=language)
return Place(self, place_details)
def add_place(self, **kwargs):
"""Adds a place to the Google Places database.
On a successful request, this method will return a dict containing
the the new Place's place_id and id in keys 'place_id' and 'id'
respectively.
keyword arguments:
name -- The full text name of the Place. Limited to 255
characters.
lat_lng -- A dict containing the following keys: lat, lng.
accuracy -- The accuracy of the location signal on which this request
is based, expressed in meters.
types -- The category in which this Place belongs. Only one type
can currently be specified for a Place. A string or
single element list may be passed in.
language -- The language in which the Place's name is being reported.
(defaults 'en').
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
required_kwargs = {'name': [str], 'lat_lng': [dict],
'accuracy': [int], 'types': [str, list]}
request_params = {}
for key in required_kwargs:
if key not in kwargs or kwargs[key] is None:
raise ValueError('The %s argument is required.' % key)
expected_types = required_kwargs[key]
type_is_valid = False
for expected_type in expected_types:
if isinstance(kwargs[key], expected_type):
type_is_valid = True
break
if not type_is_valid:
raise ValueError('Invalid value for %s' % key)
if key is not 'lat_lng':
request_params[key] = kwargs[key]
if len(kwargs['name']) > 255:
raise ValueError('The place name must not exceed 255 characters ' +
'in length.')
try:
kwargs['lat_lng']['lat']
kwargs['lat_lng']['lng']
request_params['location'] = kwargs['lat_lng']
except KeyError:
raise ValueError('Invalid keys for lat_lng.')
request_params['language'] = (kwargs.get('language')
if kwargs.get('language') is not None else
lang.ENGLISH)
sensor = (kwargs.get('sensor')
if kwargs.get('sensor') is not None else
False)
# At some point Google might support multiple types, so this supports
# strings and lists.
if isinstance(kwargs['types'], str):
request_params['types'] = [kwargs['types']]
else:
request_params['types'] = kwargs['types']
url, add_response = _fetch_remote_json(
GooglePlaces.ADD_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, add_response)
return {'place_id': add_response['place_id'],
'id': add_response['id']}
def delete_place(self, place_id, sensor=False):
"""Deletes a place from the Google Places database.
keyword arguments:
place_id -- The textual identifier that uniquely identifies this
Place, returned from a Place Search request.
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
request_params = {'place_id': place_id}
url, delete_response = _fetch_remote_json(
GooglePlaces.DELETE_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, delete_response)
def _add_required_param_keys(self):
self._request_params['key'] = self.api_key
self._request_params['sensor'] = str(self.sensor).lower()
def _generate_lat_lng_string(self, lat_lng, location):
try:
return '%(lat)s,%(lng)s' % (lat_lng if lat_lng is not None
else geocode_location(location=location, api_key=self.api_key))
except GooglePlacesError as e:
raise ValueError(
'lat_lng must be a dict with the keys, \'lat\' and \'lng\'. Cause: %s' % str(e))
@property
def request_params(self):
return self._request_params
@property
def api_key(self):
return self._api_key
@property
def sensor(self):
return self._sensor
|
slimkrazy/python-google-places | googleplaces/__init__.py | GooglePlaces.get_place | python | def get_place(self, place_id, sensor=False, language=lang.ENGLISH):
place_details = _get_place_details(place_id,
self.api_key, sensor, language=language)
return Place(self, place_details) | Gets a detailed place object.
keyword arguments:
place_id -- The unique Google identifier for the required place.
sensor -- Boolean flag denoting if the location came from a
device using its' location sensor (default False).
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH) | train | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L484-L496 | [
"def _get_place_details(place_id, api_key, sensor=False,\n language=lang.ENGLISH):\n \"\"\"Gets a detailed place response.\n\n keyword arguments:\n place_id -- The unique identifier for the required place.\n \"\"\"\n url, detail_response = _fetch_remote_json(GooglePlaces.DETAIL_... | class GooglePlaces(object):
"""A wrapper around the Google Places Query API."""
BASE_URL = 'https://maps.googleapis.com/maps/api'
PLACE_URL = BASE_URL + '/place'
GEOCODE_API_URL = BASE_URL + '/geocode/json?'
RADAR_SEARCH_API_URL = PLACE_URL + '/radarsearch/json?'
NEARBY_SEARCH_API_URL = PLACE_URL + '/nearbysearch/json?'
TEXT_SEARCH_API_URL = PLACE_URL + '/textsearch/json?'
AUTOCOMPLETE_API_URL = PLACE_URL + '/autocomplete/json?'
DETAIL_API_URL = PLACE_URL + '/details/json?'
CHECKIN_API_URL = PLACE_URL + '/check-in/json?sensor=%s&key=%s'
ADD_API_URL = PLACE_URL + '/add/json?sensor=%s&key=%s'
DELETE_API_URL = PLACE_URL + '/delete/json?sensor=%s&key=%s'
PHOTO_API_URL = PLACE_URL + '/photo?'
MAXIMUM_SEARCH_RADIUS = 50000
RESPONSE_STATUS_OK = 'OK'
RESPONSE_STATUS_ZERO_RESULTS = 'ZERO_RESULTS'
def __init__(self, api_key):
self._api_key = api_key
self._sensor = False
self._request_params = None
def query(self, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter('always')
warnings.warn('The query API is deprecated. Please use nearby_search.',
DeprecationWarning, stacklevel=2)
return self.nearby_search(**kwargs)
def nearby_search(self, language=lang.ENGLISH, keyword=None, location=None,
lat_lng=None, name=None, radius=3200, rankby=ranking.PROMINENCE,
sensor=False, type=None, types=[], pagetoken=None):
"""Perform a nearby search using the Google Places API.
One of either location, lat_lng or pagetoken are required, the rest of
the keyword arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
location -- A human readable location, e.g 'London, England'
(default None)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
name -- A term to be matched against the names of the Places.
Results will be restricted to those containing the passed
name value. (default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
rankby -- Specifies the order in which results are listed :
ranking.PROMINENCE (default) or ranking.DISTANCE
(imply no radius argument).
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
"""
if location is None and lat_lng is None and pagetoken is None:
raise ValueError('One of location, lat_lng or pagetoken must be passed in.')
if rankby == 'distance':
# As per API docs rankby == distance:
# One or more of keyword, name, or types is required.
if keyword is None and types == [] and name is None:
raise ValueError('When rankby = googleplaces.ranking.DISTANCE, ' +
'name, keyword or types kwargs ' +
'must be specified.')
self._sensor = sensor
radius = (radius if radius <= GooglePlaces.MAXIMUM_SEARCH_RADIUS
else GooglePlaces.MAXIMUM_SEARCH_RADIUS)
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params = {'location': lat_lng_str}
if rankby == 'prominence':
self._request_params['radius'] = radius
else:
self._request_params['rankby'] = rankby
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.NEARBY_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def text_search(self, query=None, language=lang.ENGLISH, lat_lng=None,
radius=3200, type=None, types=[], location=None, pagetoken=None):
"""Perform a text search using the Google Places API.
Only the one of the query or pagetoken kwargs are required, the rest of the
keyword arguments are optional.
keyword arguments:
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
query -- The text string on which to search, for example:
"Restaurant in New York".
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
"""
self._request_params = {'query': query}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.TEXT_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def autocomplete(self, input, lat_lng=None, location=None, radius=3200,
language=lang.ENGLISH, types=None, components=[]):
"""
Perform an autocomplete search using the Google Places API.
Only the input kwarg is required, the rest of the keyword arguments
are optional.
keyword arguments:
input -- The text string on which to search, for example:
"Hattie B's".
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location to which the
search is to be restricted. The maximum is 50000 meters.
(default 3200)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
types -- A type to search against. See `types.py` "autocomplete types"
for complete list
https://developers.google.com/places/documentation/autocomplete#place_types.
components -- An optional grouping of places to which you would
like to restrict your results. An array containing one or
more tuples of:
* country: matches a country name or a two letter ISO 3166-1 country code.
eg: [('country','US')]
"""
self._request_params = {'input': input}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if types:
self._request_params['types'] = types
if len(components) > 0:
self._request_params['components'] = '|'.join(['{}:{}'.format(
c[0],c[1]) for c in components])
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.AUTOCOMPLETE_API_URL, self._request_params)
_validate_response(url, places_response)
return GoogleAutocompleteSearchResult(self, places_response)
def radar_search(self, sensor=False, keyword=None, name=None,
language=lang.ENGLISH, lat_lng=None, opennow=False,
radius=3200, type=None, types=[], location=None):
"""Perform a radar search using the Google Places API.
One of lat_lng or location are required, the rest of the keyword
arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
name -- A term to be matched against the names of Places. Results will
be restricted to those containing the passed name value.
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
opennow -- Returns only those Places that are open for business at the time
the query is sent. (default False)
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param
"""
if keyword is None and name is None and len(types) is 0:
raise ValueError('One of keyword, name or types must be supplied.')
if location is None and lat_lng is None:
raise ValueError('One of location or lat_lng must be passed in.')
try:
radius = int(radius)
except:
raise ValueError('radius must be passed supplied as an integer.')
if sensor not in [True, False]:
raise ValueError('sensor must be passed in as a boolean value.')
self._request_params = {'radius': radius}
self._sensor = sensor
self._request_params['location'] = self._generate_lat_lng_string(
lat_lng, location)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if opennow is True:
self._request_params['opennow'] = 'true'
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.RADAR_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def checkin(self, place_id, sensor=False):
"""Checks in a user to a place.
keyword arguments:
place_id -- The unique Google identifier for the relevant place.
sensor -- Boolean flag denoting if the location came from a
device using its location sensor (default False).
"""
data = {'placeid': place_id}
url, checkin_response = _fetch_remote_json(
GooglePlaces.CHECKIN_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(data), use_http_post=True)
_validate_response(url, checkin_response)
def add_place(self, **kwargs):
"""Adds a place to the Google Places database.
On a successful request, this method will return a dict containing
the the new Place's place_id and id in keys 'place_id' and 'id'
respectively.
keyword arguments:
name -- The full text name of the Place. Limited to 255
characters.
lat_lng -- A dict containing the following keys: lat, lng.
accuracy -- The accuracy of the location signal on which this request
is based, expressed in meters.
types -- The category in which this Place belongs. Only one type
can currently be specified for a Place. A string or
single element list may be passed in.
language -- The language in which the Place's name is being reported.
(defaults 'en').
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
required_kwargs = {'name': [str], 'lat_lng': [dict],
'accuracy': [int], 'types': [str, list]}
request_params = {}
for key in required_kwargs:
if key not in kwargs or kwargs[key] is None:
raise ValueError('The %s argument is required.' % key)
expected_types = required_kwargs[key]
type_is_valid = False
for expected_type in expected_types:
if isinstance(kwargs[key], expected_type):
type_is_valid = True
break
if not type_is_valid:
raise ValueError('Invalid value for %s' % key)
if key is not 'lat_lng':
request_params[key] = kwargs[key]
if len(kwargs['name']) > 255:
raise ValueError('The place name must not exceed 255 characters ' +
'in length.')
try:
kwargs['lat_lng']['lat']
kwargs['lat_lng']['lng']
request_params['location'] = kwargs['lat_lng']
except KeyError:
raise ValueError('Invalid keys for lat_lng.')
request_params['language'] = (kwargs.get('language')
if kwargs.get('language') is not None else
lang.ENGLISH)
sensor = (kwargs.get('sensor')
if kwargs.get('sensor') is not None else
False)
# At some point Google might support multiple types, so this supports
# strings and lists.
if isinstance(kwargs['types'], str):
request_params['types'] = [kwargs['types']]
else:
request_params['types'] = kwargs['types']
url, add_response = _fetch_remote_json(
GooglePlaces.ADD_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, add_response)
return {'place_id': add_response['place_id'],
'id': add_response['id']}
def delete_place(self, place_id, sensor=False):
"""Deletes a place from the Google Places database.
keyword arguments:
place_id -- The textual identifier that uniquely identifies this
Place, returned from a Place Search request.
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
request_params = {'place_id': place_id}
url, delete_response = _fetch_remote_json(
GooglePlaces.DELETE_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, delete_response)
def _add_required_param_keys(self):
self._request_params['key'] = self.api_key
self._request_params['sensor'] = str(self.sensor).lower()
def _generate_lat_lng_string(self, lat_lng, location):
try:
return '%(lat)s,%(lng)s' % (lat_lng if lat_lng is not None
else geocode_location(location=location, api_key=self.api_key))
except GooglePlacesError as e:
raise ValueError(
'lat_lng must be a dict with the keys, \'lat\' and \'lng\'. Cause: %s' % str(e))
@property
def request_params(self):
return self._request_params
@property
def api_key(self):
return self._api_key
@property
def sensor(self):
return self._sensor
|
slimkrazy/python-google-places | googleplaces/__init__.py | GooglePlaces.add_place | python | def add_place(self, **kwargs):
required_kwargs = {'name': [str], 'lat_lng': [dict],
'accuracy': [int], 'types': [str, list]}
request_params = {}
for key in required_kwargs:
if key not in kwargs or kwargs[key] is None:
raise ValueError('The %s argument is required.' % key)
expected_types = required_kwargs[key]
type_is_valid = False
for expected_type in expected_types:
if isinstance(kwargs[key], expected_type):
type_is_valid = True
break
if not type_is_valid:
raise ValueError('Invalid value for %s' % key)
if key is not 'lat_lng':
request_params[key] = kwargs[key]
if len(kwargs['name']) > 255:
raise ValueError('The place name must not exceed 255 characters ' +
'in length.')
try:
kwargs['lat_lng']['lat']
kwargs['lat_lng']['lng']
request_params['location'] = kwargs['lat_lng']
except KeyError:
raise ValueError('Invalid keys for lat_lng.')
request_params['language'] = (kwargs.get('language')
if kwargs.get('language') is not None else
lang.ENGLISH)
sensor = (kwargs.get('sensor')
if kwargs.get('sensor') is not None else
False)
# At some point Google might support multiple types, so this supports
# strings and lists.
if isinstance(kwargs['types'], str):
request_params['types'] = [kwargs['types']]
else:
request_params['types'] = kwargs['types']
url, add_response = _fetch_remote_json(
GooglePlaces.ADD_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, add_response)
return {'place_id': add_response['place_id'],
'id': add_response['id']} | Adds a place to the Google Places database.
On a successful request, this method will return a dict containing
the the new Place's place_id and id in keys 'place_id' and 'id'
respectively.
keyword arguments:
name -- The full text name of the Place. Limited to 255
characters.
lat_lng -- A dict containing the following keys: lat, lng.
accuracy -- The accuracy of the location signal on which this request
is based, expressed in meters.
types -- The category in which this Place belongs. Only one type
can currently be specified for a Place. A string or
single element list may be passed in.
language -- The language in which the Place's name is being reported.
(defaults 'en').
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False). | train | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L498-L565 | [
"def _fetch_remote_json(service_url, params=None, use_http_post=False):\n \"\"\"Retrieves a JSON object from a URL.\"\"\"\n if not params:\n params = {}\n\n request_url, response = _fetch_remote(service_url, params, use_http_post)\n if six.PY3:\n str_response = response.read().decode('utf-... | class GooglePlaces(object):
"""A wrapper around the Google Places Query API."""
BASE_URL = 'https://maps.googleapis.com/maps/api'
PLACE_URL = BASE_URL + '/place'
GEOCODE_API_URL = BASE_URL + '/geocode/json?'
RADAR_SEARCH_API_URL = PLACE_URL + '/radarsearch/json?'
NEARBY_SEARCH_API_URL = PLACE_URL + '/nearbysearch/json?'
TEXT_SEARCH_API_URL = PLACE_URL + '/textsearch/json?'
AUTOCOMPLETE_API_URL = PLACE_URL + '/autocomplete/json?'
DETAIL_API_URL = PLACE_URL + '/details/json?'
CHECKIN_API_URL = PLACE_URL + '/check-in/json?sensor=%s&key=%s'
ADD_API_URL = PLACE_URL + '/add/json?sensor=%s&key=%s'
DELETE_API_URL = PLACE_URL + '/delete/json?sensor=%s&key=%s'
PHOTO_API_URL = PLACE_URL + '/photo?'
MAXIMUM_SEARCH_RADIUS = 50000
RESPONSE_STATUS_OK = 'OK'
RESPONSE_STATUS_ZERO_RESULTS = 'ZERO_RESULTS'
def __init__(self, api_key):
self._api_key = api_key
self._sensor = False
self._request_params = None
def query(self, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter('always')
warnings.warn('The query API is deprecated. Please use nearby_search.',
DeprecationWarning, stacklevel=2)
return self.nearby_search(**kwargs)
def nearby_search(self, language=lang.ENGLISH, keyword=None, location=None,
lat_lng=None, name=None, radius=3200, rankby=ranking.PROMINENCE,
sensor=False, type=None, types=[], pagetoken=None):
"""Perform a nearby search using the Google Places API.
One of either location, lat_lng or pagetoken are required, the rest of
the keyword arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
location -- A human readable location, e.g 'London, England'
(default None)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
name -- A term to be matched against the names of the Places.
Results will be restricted to those containing the passed
name value. (default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
rankby -- Specifies the order in which results are listed :
ranking.PROMINENCE (default) or ranking.DISTANCE
(imply no radius argument).
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
"""
if location is None and lat_lng is None and pagetoken is None:
raise ValueError('One of location, lat_lng or pagetoken must be passed in.')
if rankby == 'distance':
# As per API docs rankby == distance:
# One or more of keyword, name, or types is required.
if keyword is None and types == [] and name is None:
raise ValueError('When rankby = googleplaces.ranking.DISTANCE, ' +
'name, keyword or types kwargs ' +
'must be specified.')
self._sensor = sensor
radius = (radius if radius <= GooglePlaces.MAXIMUM_SEARCH_RADIUS
else GooglePlaces.MAXIMUM_SEARCH_RADIUS)
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params = {'location': lat_lng_str}
if rankby == 'prominence':
self._request_params['radius'] = radius
else:
self._request_params['rankby'] = rankby
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.NEARBY_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def text_search(self, query=None, language=lang.ENGLISH, lat_lng=None,
radius=3200, type=None, types=[], location=None, pagetoken=None):
"""Perform a text search using the Google Places API.
Only the one of the query or pagetoken kwargs are required, the rest of the
keyword arguments are optional.
keyword arguments:
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
query -- The text string on which to search, for example:
"Restaurant in New York".
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
"""
self._request_params = {'query': query}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.TEXT_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def autocomplete(self, input, lat_lng=None, location=None, radius=3200,
language=lang.ENGLISH, types=None, components=[]):
"""
Perform an autocomplete search using the Google Places API.
Only the input kwarg is required, the rest of the keyword arguments
are optional.
keyword arguments:
input -- The text string on which to search, for example:
"Hattie B's".
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location to which the
search is to be restricted. The maximum is 50000 meters.
(default 3200)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
types -- A type to search against. See `types.py` "autocomplete types"
for complete list
https://developers.google.com/places/documentation/autocomplete#place_types.
components -- An optional grouping of places to which you would
like to restrict your results. An array containing one or
more tuples of:
* country: matches a country name or a two letter ISO 3166-1 country code.
eg: [('country','US')]
"""
self._request_params = {'input': input}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if types:
self._request_params['types'] = types
if len(components) > 0:
self._request_params['components'] = '|'.join(['{}:{}'.format(
c[0],c[1]) for c in components])
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.AUTOCOMPLETE_API_URL, self._request_params)
_validate_response(url, places_response)
return GoogleAutocompleteSearchResult(self, places_response)
def radar_search(self, sensor=False, keyword=None, name=None,
language=lang.ENGLISH, lat_lng=None, opennow=False,
radius=3200, type=None, types=[], location=None):
"""Perform a radar search using the Google Places API.
One of lat_lng or location are required, the rest of the keyword
arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
name -- A term to be matched against the names of Places. Results will
be restricted to those containing the passed name value.
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
opennow -- Returns only those Places that are open for business at the time
the query is sent. (default False)
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param
"""
if keyword is None and name is None and len(types) is 0:
raise ValueError('One of keyword, name or types must be supplied.')
if location is None and lat_lng is None:
raise ValueError('One of location or lat_lng must be passed in.')
try:
radius = int(radius)
except:
raise ValueError('radius must be passed supplied as an integer.')
if sensor not in [True, False]:
raise ValueError('sensor must be passed in as a boolean value.')
self._request_params = {'radius': radius}
self._sensor = sensor
self._request_params['location'] = self._generate_lat_lng_string(
lat_lng, location)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if opennow is True:
self._request_params['opennow'] = 'true'
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.RADAR_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def checkin(self, place_id, sensor=False):
"""Checks in a user to a place.
keyword arguments:
place_id -- The unique Google identifier for the relevant place.
sensor -- Boolean flag denoting if the location came from a
device using its location sensor (default False).
"""
data = {'placeid': place_id}
url, checkin_response = _fetch_remote_json(
GooglePlaces.CHECKIN_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(data), use_http_post=True)
_validate_response(url, checkin_response)
def get_place(self, place_id, sensor=False, language=lang.ENGLISH):
"""Gets a detailed place object.
keyword arguments:
place_id -- The unique Google identifier for the required place.
sensor -- Boolean flag denoting if the location came from a
device using its' location sensor (default False).
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
"""
place_details = _get_place_details(place_id,
self.api_key, sensor, language=language)
return Place(self, place_details)
def delete_place(self, place_id, sensor=False):
"""Deletes a place from the Google Places database.
keyword arguments:
place_id -- The textual identifier that uniquely identifies this
Place, returned from a Place Search request.
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
request_params = {'place_id': place_id}
url, delete_response = _fetch_remote_json(
GooglePlaces.DELETE_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, delete_response)
def _add_required_param_keys(self):
self._request_params['key'] = self.api_key
self._request_params['sensor'] = str(self.sensor).lower()
def _generate_lat_lng_string(self, lat_lng, location):
try:
return '%(lat)s,%(lng)s' % (lat_lng if lat_lng is not None
else geocode_location(location=location, api_key=self.api_key))
except GooglePlacesError as e:
raise ValueError(
'lat_lng must be a dict with the keys, \'lat\' and \'lng\'. Cause: %s' % str(e))
@property
def request_params(self):
return self._request_params
@property
def api_key(self):
return self._api_key
@property
def sensor(self):
return self._sensor
|
slimkrazy/python-google-places | googleplaces/__init__.py | GooglePlaces.delete_place | python | def delete_place(self, place_id, sensor=False):
request_params = {'place_id': place_id}
url, delete_response = _fetch_remote_json(
GooglePlaces.DELETE_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, delete_response) | Deletes a place from the Google Places database.
keyword arguments:
place_id -- The textual identifier that uniquely identifies this
Place, returned from a Place Search request.
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False). | train | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L567-L581 | [
"def _fetch_remote_json(service_url, params=None, use_http_post=False):\n \"\"\"Retrieves a JSON object from a URL.\"\"\"\n if not params:\n params = {}\n\n request_url, response = _fetch_remote(service_url, params, use_http_post)\n if six.PY3:\n str_response = response.read().decode('utf-... | class GooglePlaces(object):
"""A wrapper around the Google Places Query API."""
BASE_URL = 'https://maps.googleapis.com/maps/api'
PLACE_URL = BASE_URL + '/place'
GEOCODE_API_URL = BASE_URL + '/geocode/json?'
RADAR_SEARCH_API_URL = PLACE_URL + '/radarsearch/json?'
NEARBY_SEARCH_API_URL = PLACE_URL + '/nearbysearch/json?'
TEXT_SEARCH_API_URL = PLACE_URL + '/textsearch/json?'
AUTOCOMPLETE_API_URL = PLACE_URL + '/autocomplete/json?'
DETAIL_API_URL = PLACE_URL + '/details/json?'
CHECKIN_API_URL = PLACE_URL + '/check-in/json?sensor=%s&key=%s'
ADD_API_URL = PLACE_URL + '/add/json?sensor=%s&key=%s'
DELETE_API_URL = PLACE_URL + '/delete/json?sensor=%s&key=%s'
PHOTO_API_URL = PLACE_URL + '/photo?'
MAXIMUM_SEARCH_RADIUS = 50000
RESPONSE_STATUS_OK = 'OK'
RESPONSE_STATUS_ZERO_RESULTS = 'ZERO_RESULTS'
def __init__(self, api_key):
self._api_key = api_key
self._sensor = False
self._request_params = None
def query(self, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter('always')
warnings.warn('The query API is deprecated. Please use nearby_search.',
DeprecationWarning, stacklevel=2)
return self.nearby_search(**kwargs)
def nearby_search(self, language=lang.ENGLISH, keyword=None, location=None,
lat_lng=None, name=None, radius=3200, rankby=ranking.PROMINENCE,
sensor=False, type=None, types=[], pagetoken=None):
"""Perform a nearby search using the Google Places API.
One of either location, lat_lng or pagetoken are required, the rest of
the keyword arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
location -- A human readable location, e.g 'London, England'
(default None)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
name -- A term to be matched against the names of the Places.
Results will be restricted to those containing the passed
name value. (default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
rankby -- Specifies the order in which results are listed :
ranking.PROMINENCE (default) or ranking.DISTANCE
(imply no radius argument).
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
"""
if location is None and lat_lng is None and pagetoken is None:
raise ValueError('One of location, lat_lng or pagetoken must be passed in.')
if rankby == 'distance':
# As per API docs rankby == distance:
# One or more of keyword, name, or types is required.
if keyword is None and types == [] and name is None:
raise ValueError('When rankby = googleplaces.ranking.DISTANCE, ' +
'name, keyword or types kwargs ' +
'must be specified.')
self._sensor = sensor
radius = (radius if radius <= GooglePlaces.MAXIMUM_SEARCH_RADIUS
else GooglePlaces.MAXIMUM_SEARCH_RADIUS)
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params = {'location': lat_lng_str}
if rankby == 'prominence':
self._request_params['radius'] = radius
else:
self._request_params['rankby'] = rankby
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.NEARBY_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def text_search(self, query=None, language=lang.ENGLISH, lat_lng=None,
radius=3200, type=None, types=[], location=None, pagetoken=None):
"""Perform a text search using the Google Places API.
Only the one of the query or pagetoken kwargs are required, the rest of the
keyword arguments are optional.
keyword arguments:
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
pagetoken-- Optional parameter to force the search result to return the next
20 results from a previously run search. Setting this parameter
will execute a search with the same parameters used previously.
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
query -- The text string on which to search, for example:
"Restaurant in New York".
type -- Optional type param used to indicate place category.
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param.
"""
self._request_params = {'query': query}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if pagetoken is not None:
self._request_params['pagetoken'] = pagetoken
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.TEXT_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def autocomplete(self, input, lat_lng=None, location=None, radius=3200,
language=lang.ENGLISH, types=None, components=[]):
"""
Perform an autocomplete search using the Google Places API.
Only the input kwarg is required, the rest of the keyword arguments
are optional.
keyword arguments:
input -- The text string on which to search, for example:
"Hattie B's".
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location to which the
search is to be restricted. The maximum is 50000 meters.
(default 3200)
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
types -- A type to search against. See `types.py` "autocomplete types"
for complete list
https://developers.google.com/places/documentation/autocomplete#place_types.
components -- An optional grouping of places to which you would
like to restrict your results. An array containing one or
more tuples of:
* country: matches a country name or a two letter ISO 3166-1 country code.
eg: [('country','US')]
"""
self._request_params = {'input': input}
if lat_lng is not None or location is not None:
lat_lng_str = self._generate_lat_lng_string(lat_lng, location)
self._request_params['location'] = lat_lng_str
self._request_params['radius'] = radius
if types:
self._request_params['types'] = types
if len(components) > 0:
self._request_params['components'] = '|'.join(['{}:{}'.format(
c[0],c[1]) for c in components])
if language is not None:
self._request_params['language'] = language
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.AUTOCOMPLETE_API_URL, self._request_params)
_validate_response(url, places_response)
return GoogleAutocompleteSearchResult(self, places_response)
def radar_search(self, sensor=False, keyword=None, name=None,
language=lang.ENGLISH, lat_lng=None, opennow=False,
radius=3200, type=None, types=[], location=None):
"""Perform a radar search using the Google Places API.
One of lat_lng or location are required, the rest of the keyword
arguments are optional.
keyword arguments:
keyword -- A term to be matched against all available fields, including
but not limited to name, type, and address (default None)
name -- A term to be matched against the names of Places. Results will
be restricted to those containing the passed name value.
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
lat_lng -- A dict containing the following keys: lat, lng
(default None)
location -- A human readable location, e.g 'London, England'
(default None)
radius -- The radius (in meters) around the location/lat_lng to
restrict the search to. The maximum is 50000 meters.
(default 3200)
opennow -- Returns only those Places that are open for business at the time
the query is sent. (default False)
sensor -- Indicates whether or not the Place request came from a
device using a location sensor (default False).
type -- Optional type param used to indicate place category
types -- An optional list of types, restricting the results to
Places (default []). If there is only one item the request
will be send as type param
"""
if keyword is None and name is None and len(types) is 0:
raise ValueError('One of keyword, name or types must be supplied.')
if location is None and lat_lng is None:
raise ValueError('One of location or lat_lng must be passed in.')
try:
radius = int(radius)
except:
raise ValueError('radius must be passed supplied as an integer.')
if sensor not in [True, False]:
raise ValueError('sensor must be passed in as a boolean value.')
self._request_params = {'radius': radius}
self._sensor = sensor
self._request_params['location'] = self._generate_lat_lng_string(
lat_lng, location)
if keyword is not None:
self._request_params['keyword'] = keyword
if name is not None:
self._request_params['name'] = name
if type:
self._request_params['type'] = type
elif types:
if len(types) == 1:
self._request_params['type'] = types[0]
elif len(types) > 1:
self._request_params['types'] = '|'.join(types)
if language is not None:
self._request_params['language'] = language
if opennow is True:
self._request_params['opennow'] = 'true'
self._add_required_param_keys()
url, places_response = _fetch_remote_json(
GooglePlaces.RADAR_SEARCH_API_URL, self._request_params)
_validate_response(url, places_response)
return GooglePlacesSearchResult(self, places_response)
def checkin(self, place_id, sensor=False):
"""Checks in a user to a place.
keyword arguments:
place_id -- The unique Google identifier for the relevant place.
sensor -- Boolean flag denoting if the location came from a
device using its location sensor (default False).
"""
data = {'placeid': place_id}
url, checkin_response = _fetch_remote_json(
GooglePlaces.CHECKIN_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(data), use_http_post=True)
_validate_response(url, checkin_response)
def get_place(self, place_id, sensor=False, language=lang.ENGLISH):
"""Gets a detailed place object.
keyword arguments:
place_id -- The unique Google identifier for the required place.
sensor -- Boolean flag denoting if the location came from a
device using its' location sensor (default False).
language -- The language code, indicating in which language the
results should be returned, if possible. (default lang.ENGLISH)
"""
place_details = _get_place_details(place_id,
self.api_key, sensor, language=language)
return Place(self, place_details)
def add_place(self, **kwargs):
"""Adds a place to the Google Places database.
On a successful request, this method will return a dict containing
the the new Place's place_id and id in keys 'place_id' and 'id'
respectively.
keyword arguments:
name -- The full text name of the Place. Limited to 255
characters.
lat_lng -- A dict containing the following keys: lat, lng.
accuracy -- The accuracy of the location signal on which this request
is based, expressed in meters.
types -- The category in which this Place belongs. Only one type
can currently be specified for a Place. A string or
single element list may be passed in.
language -- The language in which the Place's name is being reported.
(defaults 'en').
sensor -- Boolean flag denoting if the location came from a device
using its location sensor (default False).
"""
required_kwargs = {'name': [str], 'lat_lng': [dict],
'accuracy': [int], 'types': [str, list]}
request_params = {}
for key in required_kwargs:
if key not in kwargs or kwargs[key] is None:
raise ValueError('The %s argument is required.' % key)
expected_types = required_kwargs[key]
type_is_valid = False
for expected_type in expected_types:
if isinstance(kwargs[key], expected_type):
type_is_valid = True
break
if not type_is_valid:
raise ValueError('Invalid value for %s' % key)
if key is not 'lat_lng':
request_params[key] = kwargs[key]
if len(kwargs['name']) > 255:
raise ValueError('The place name must not exceed 255 characters ' +
'in length.')
try:
kwargs['lat_lng']['lat']
kwargs['lat_lng']['lng']
request_params['location'] = kwargs['lat_lng']
except KeyError:
raise ValueError('Invalid keys for lat_lng.')
request_params['language'] = (kwargs.get('language')
if kwargs.get('language') is not None else
lang.ENGLISH)
sensor = (kwargs.get('sensor')
if kwargs.get('sensor') is not None else
False)
# At some point Google might support multiple types, so this supports
# strings and lists.
if isinstance(kwargs['types'], str):
request_params['types'] = [kwargs['types']]
else:
request_params['types'] = kwargs['types']
url, add_response = _fetch_remote_json(
GooglePlaces.ADD_API_URL % (str(sensor).lower(),
self.api_key), json.dumps(request_params), use_http_post=True)
_validate_response(url, add_response)
return {'place_id': add_response['place_id'],
'id': add_response['id']}
def _add_required_param_keys(self):
self._request_params['key'] = self.api_key
self._request_params['sensor'] = str(self.sensor).lower()
def _generate_lat_lng_string(self, lat_lng, location):
try:
return '%(lat)s,%(lng)s' % (lat_lng if lat_lng is not None
else geocode_location(location=location, api_key=self.api_key))
except GooglePlacesError as e:
raise ValueError(
'lat_lng must be a dict with the keys, \'lat\' and \'lng\'. Cause: %s' % str(e))
@property
def request_params(self):
return self._request_params
@property
def api_key(self):
return self._api_key
@property
def sensor(self):
return self._sensor
|
slimkrazy/python-google-places | googleplaces/__init__.py | Prediction.types | python | def types(self):
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types | Returns a list of feature types describing the given result. | train | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L723-L729 | null | class Prediction(object):
"""
Represents a prediction from the results of a Google Places Autocomplete API query.
"""
def __init__(self, query_instance, prediction):
self._query_instance = query_instance
self._description = prediction['description']
self._id = prediction['id']
self._matched_substrings = prediction['matched_substrings']
self._place_id = prediction['place_id']
self._reference = prediction['reference']
self._terms = prediction['terms']
self._types = prediction.get('types',[])
if prediction.get('_description') is None:
self._place = None
else:
self._place = prediction
@property
def description(self):
"""
String representation of a Prediction location. Generally contains
name, country, and elements contained in the terms property.
"""
return self._description
@property
def id(self):
"""
Returns the deprecated id property.
This identifier may not be used to retrieve information about this
place, but is guaranteed to be valid across sessions. It can be used
to consolidate data about this Place, and to verify the identity of a
Place across separate searches.
This property is deprecated:
https://developers.google.com/places/documentation/autocomplete#deprecation
"""
return self._id
@property
def matched_substrings(self):
"""
Returns the placement and offset of the matched strings for this search.
A an array of dicts, each with the keys 'length' and 'offset', will be returned.
"""
return self._matched_substrings
@property
def place_id(self):
"""
Returns the unique stable identifier denoting this place.
This identifier may be used to retrieve information about this
place.
This should be considered the primary identifier of a place.
"""
return self._place_id
@property
def reference(self):
"""
Returns the deprecated reference property.
The token can be used to retrieve additional information about this
place when invoking the getPlace method on an GooglePlaces instance.
You can store this token and use it at any time in future to refresh
cached data about this Place, but the same token is not guaranteed to
be returned for any given Place across different searches.
This property is deprecated:
https://developers.google.com/places/documentation/autocomplete#deprecation
"""
return self._reference
@property
def terms(self):
"""
A list of terms which build up the description string
A an array of dicts, each with the keys `offset` and `value`, will be returned.
"""
return self._terms
@property
# The following properties require a further API call in order to be
# available.
@property
def place(self):
"""
Returns the JSON response from Google Places Detail search API.
"""
self._validate_status()
return self._place
def get_details(self, language=None):
"""
Retrieves full information on the place matching the place_id.
Stores the response in the `place` property.
"""
if self._place is None:
if language is None:
try:
language = self._query_instance._request_params['language']
except KeyError:
language = lang.ENGLISH
place = _get_place_details(
self.place_id, self._query_instance.api_key,
self._query_instance.sensor, language=language)
self._place = Place(self._query_instance, place)
def _validate_status(self):
"""
Indicates specific properties are only available after a details call.
"""
if self._place is None:
error_detail = ('The attribute requested is only available after ' +
'an explicit call to get_details() is made.')
raise GooglePlacesAttributeError(error_detail)
def __repr__(self):
""" Return a string representation with description. """
return '<{} description="{}">'.format(self.__class__.__name__, self.description)
|
slimkrazy/python-google-places | googleplaces/__init__.py | Prediction.get_details | python | def get_details(self, language=None):
if self._place is None:
if language is None:
try:
language = self._query_instance._request_params['language']
except KeyError:
language = lang.ENGLISH
place = _get_place_details(
self.place_id, self._query_instance.api_key,
self._query_instance.sensor, language=language)
self._place = Place(self._query_instance, place) | Retrieves full information on the place matching the place_id.
Stores the response in the `place` property. | train | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L741-L756 | [
"def _get_place_details(place_id, api_key, sensor=False,\n language=lang.ENGLISH):\n \"\"\"Gets a detailed place response.\n\n keyword arguments:\n place_id -- The unique identifier for the required place.\n \"\"\"\n url, detail_response = _fetch_remote_json(GooglePlaces.DETAIL_... | class Prediction(object):
"""
Represents a prediction from the results of a Google Places Autocomplete API query.
"""
def __init__(self, query_instance, prediction):
self._query_instance = query_instance
self._description = prediction['description']
self._id = prediction['id']
self._matched_substrings = prediction['matched_substrings']
self._place_id = prediction['place_id']
self._reference = prediction['reference']
self._terms = prediction['terms']
self._types = prediction.get('types',[])
if prediction.get('_description') is None:
self._place = None
else:
self._place = prediction
@property
def description(self):
"""
String representation of a Prediction location. Generally contains
name, country, and elements contained in the terms property.
"""
return self._description
@property
def id(self):
"""
Returns the deprecated id property.
This identifier may not be used to retrieve information about this
place, but is guaranteed to be valid across sessions. It can be used
to consolidate data about this Place, and to verify the identity of a
Place across separate searches.
This property is deprecated:
https://developers.google.com/places/documentation/autocomplete#deprecation
"""
return self._id
@property
def matched_substrings(self):
"""
Returns the placement and offset of the matched strings for this search.
A an array of dicts, each with the keys 'length' and 'offset', will be returned.
"""
return self._matched_substrings
@property
def place_id(self):
"""
Returns the unique stable identifier denoting this place.
This identifier may be used to retrieve information about this
place.
This should be considered the primary identifier of a place.
"""
return self._place_id
@property
def reference(self):
"""
Returns the deprecated reference property.
The token can be used to retrieve additional information about this
place when invoking the getPlace method on an GooglePlaces instance.
You can store this token and use it at any time in future to refresh
cached data about this Place, but the same token is not guaranteed to
be returned for any given Place across different searches.
This property is deprecated:
https://developers.google.com/places/documentation/autocomplete#deprecation
"""
return self._reference
@property
def terms(self):
"""
A list of terms which build up the description string
A an array of dicts, each with the keys `offset` and `value`, will be returned.
"""
return self._terms
@property
def types(self):
"""
Returns a list of feature types describing the given result.
"""
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types
# The following properties require a further API call in order to be
# available.
@property
def place(self):
"""
Returns the JSON response from Google Places Detail search API.
"""
self._validate_status()
return self._place
def _validate_status(self):
"""
Indicates specific properties are only available after a details call.
"""
if self._place is None:
error_detail = ('The attribute requested is only available after ' +
'an explicit call to get_details() is made.')
raise GooglePlacesAttributeError(error_detail)
def __repr__(self):
""" Return a string representation with description. """
return '<{} description="{}">'.format(self.__class__.__name__, self.description)
|
slimkrazy/python-google-places | googleplaces/__init__.py | Place.icon | python | def icon(self):
if self._icon == '' and self.details != None and 'icon' in self.details:
self._icon = self.details['icon']
return self._icon | Returns the URL of a recommended icon for display. | train | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L893-L897 | null | class Place(object):
"""
Represents a place from the results of a Google Places API query.
"""
def __init__(self, query_instance, place_data):
self._query_instance = query_instance
self._place_id = place_data['place_id']
self._id = place_data.get('id', '')
self._reference = place_data.get('reference', '')
self._name = place_data.get('name','')
self._vicinity = place_data.get('vicinity', '')
self._geo_location = place_data['geometry']['location']
self._rating = place_data.get('rating','')
self._types = place_data.get('types','')
self._icon = place_data.get('icon','')
if place_data.get('address_components') is None:
self._details = None
else:
self._details = place_data
@property
def reference(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns contains a unique token for the place.
The token can be used to retrieve additional information about this
place when invoking the getPlace method on an GooglePlaces instance.
You can store this token and use it at any time in future to refresh
cached data about this Place, but the same token is not guaranteed to
be returned for any given Place across different searches."""
warnings.warn('The "reference" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._reference
@property
def id(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns the unique stable identifier denoting this place.
This identifier may not be used to retrieve information about this
place, but is guaranteed to be valid across sessions. It can be used
to consolidate data about this Place, and to verify the identity of a
Place across separate searches.
"""
warnings.warn('The "id" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._id
@property
def place_id(self):
"""Returns the unique stable identifier denoting this place.
This identifier may be used to retrieve information about this
place.
This should be considered the primary identifier of a place.
"""
return self._place_id
@property
@property
def types(self):
"""Returns a list of feature types describing the given result."""
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types
@property
def geo_location(self):
"""Returns the lat lng co-ordinates of the place.
A dict with the keys 'lat' and 'lng' will be returned.
"""
return self._geo_location
@property
def name(self):
"""Returns the human-readable name of the place."""
if self._name == '' and self.details != None and 'name' in self.details:
self._name = self.details['name']
return self._name
@property
def vicinity(self):
"""Returns a feature name of a nearby location.
Often this feature refers to a street or neighborhood within the given
results.
"""
if self._vicinity == '' and self.details != None and 'vicinity' in self.details:
self._vicinity = self.details['vicinity']
return self._vicinity
@property
def rating(self):
"""Returns the Place's rating, from 0.0 to 5.0, based on user reviews.
This method will return None for places that have no rating.
"""
if self._rating == '' and self.details != None and 'rating' in self.details:
self._rating = self.details['rating']
return self._rating
# The following properties require a further API call in order to be
# available.
@property
def details(self):
"""Returns the JSON response from Google Places Detail search API."""
self._validate_status()
return self._details
@property
def formatted_address(self):
"""Returns a string containing the human-readable address of this place.
Often this address is equivalent to the "postal address," which
sometimes differs from country to country. (Note that some countries,
such as the United Kingdom, do not allow distribution of complete postal
addresses due to licensing restrictions.)
"""
self._validate_status()
return self.details.get('formatted_address')
@property
def local_phone_number(self):
"""Returns the Place's phone number in its local format."""
self._validate_status()
return self.details.get('formatted_phone_number')
@property
def international_phone_number(self):
self._validate_status()
return self.details.get('international_phone_number')
@property
def website(self):
"""Returns the authoritative website for this Place."""
self._validate_status()
return self.details.get('website')
@property
def url(self):
"""Contains the official Google Place Page URL of this establishment.
Applications must link to or embed the Google Place page on any screen
that shows detailed results about this Place to the user.
"""
self._validate_status()
return self.details.get('url')
@property
def html_attributions(self):
"""Returns the HTML attributions for the specified response.
Any returned HTML attributions MUST be displayed as-is, in accordance
with the requirements as found in the documentation. Please see the
module comments for links to the relevant url.
"""
self._validate_status()
return self.details.get('html_attributions', [])
@property
def has_attributions(self):
"""Returns a flag denoting if the response had any html attributions."""
return (False if self._details is None else
len(self.html_attributions) > 0)
def checkin(self):
"""Checks in an anonymous user in."""
self._query_instance.checkin(self.place_id,
self._query_instance.sensor)
def get_details(self, language=None):
"""Retrieves full information on the place matching the place_id.
Further attributes will be made available on the instance once this
method has been invoked.
keyword arguments:
language -- The language code, indicating in which language the
results should be returned, if possible. This value defaults
to the language that was used to generate the
GooglePlacesSearchResult instance.
"""
if self._details is None:
if language is None:
try:
language = self._query_instance._request_params['language']
except KeyError:
language = lang.ENGLISH
self._details = _get_place_details(
self.place_id, self._query_instance.api_key,
self._query_instance.sensor, language=language)
@cached_property
def photos(self):
self.get_details()
return [Photo(self._query_instance, i)
for i in self.details.get('photos', [])]
def _validate_status(self):
if self._details is None:
error_detail = ('The attribute requested is only available after ' +
'an explicit call to get_details() is made.')
raise GooglePlacesAttributeError(error_detail)
def __repr__(self):
""" Return a string representation including the name, lat, and lng. """
return '<{} name="{}", lat={}, lng={}>'.format(
self.__class__.__name__,
self.name,
self.geo_location['lat'],
self.geo_location['lng']
)
|
slimkrazy/python-google-places | googleplaces/__init__.py | Place.name | python | def name(self):
if self._name == '' and self.details != None and 'name' in self.details:
self._name = self.details['name']
return self._name | Returns the human-readable name of the place. | train | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L915-L919 | null | class Place(object):
"""
Represents a place from the results of a Google Places API query.
"""
def __init__(self, query_instance, place_data):
self._query_instance = query_instance
self._place_id = place_data['place_id']
self._id = place_data.get('id', '')
self._reference = place_data.get('reference', '')
self._name = place_data.get('name','')
self._vicinity = place_data.get('vicinity', '')
self._geo_location = place_data['geometry']['location']
self._rating = place_data.get('rating','')
self._types = place_data.get('types','')
self._icon = place_data.get('icon','')
if place_data.get('address_components') is None:
self._details = None
else:
self._details = place_data
@property
def reference(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns contains a unique token for the place.
The token can be used to retrieve additional information about this
place when invoking the getPlace method on an GooglePlaces instance.
You can store this token and use it at any time in future to refresh
cached data about this Place, but the same token is not guaranteed to
be returned for any given Place across different searches."""
warnings.warn('The "reference" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._reference
@property
def id(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns the unique stable identifier denoting this place.
This identifier may not be used to retrieve information about this
place, but is guaranteed to be valid across sessions. It can be used
to consolidate data about this Place, and to verify the identity of a
Place across separate searches.
"""
warnings.warn('The "id" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._id
@property
def place_id(self):
"""Returns the unique stable identifier denoting this place.
This identifier may be used to retrieve information about this
place.
This should be considered the primary identifier of a place.
"""
return self._place_id
@property
def icon(self):
"""Returns the URL of a recommended icon for display."""
if self._icon == '' and self.details != None and 'icon' in self.details:
self._icon = self.details['icon']
return self._icon
@property
def types(self):
"""Returns a list of feature types describing the given result."""
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types
@property
def geo_location(self):
"""Returns the lat lng co-ordinates of the place.
A dict with the keys 'lat' and 'lng' will be returned.
"""
return self._geo_location
@property
@property
def vicinity(self):
"""Returns a feature name of a nearby location.
Often this feature refers to a street or neighborhood within the given
results.
"""
if self._vicinity == '' and self.details != None and 'vicinity' in self.details:
self._vicinity = self.details['vicinity']
return self._vicinity
@property
def rating(self):
"""Returns the Place's rating, from 0.0 to 5.0, based on user reviews.
This method will return None for places that have no rating.
"""
if self._rating == '' and self.details != None and 'rating' in self.details:
self._rating = self.details['rating']
return self._rating
# The following properties require a further API call in order to be
# available.
@property
def details(self):
"""Returns the JSON response from Google Places Detail search API."""
self._validate_status()
return self._details
@property
def formatted_address(self):
"""Returns a string containing the human-readable address of this place.
Often this address is equivalent to the "postal address," which
sometimes differs from country to country. (Note that some countries,
such as the United Kingdom, do not allow distribution of complete postal
addresses due to licensing restrictions.)
"""
self._validate_status()
return self.details.get('formatted_address')
@property
def local_phone_number(self):
"""Returns the Place's phone number in its local format."""
self._validate_status()
return self.details.get('formatted_phone_number')
@property
def international_phone_number(self):
self._validate_status()
return self.details.get('international_phone_number')
@property
def website(self):
"""Returns the authoritative website for this Place."""
self._validate_status()
return self.details.get('website')
@property
def url(self):
"""Contains the official Google Place Page URL of this establishment.
Applications must link to or embed the Google Place page on any screen
that shows detailed results about this Place to the user.
"""
self._validate_status()
return self.details.get('url')
@property
def html_attributions(self):
"""Returns the HTML attributions for the specified response.
Any returned HTML attributions MUST be displayed as-is, in accordance
with the requirements as found in the documentation. Please see the
module comments for links to the relevant url.
"""
self._validate_status()
return self.details.get('html_attributions', [])
@property
def has_attributions(self):
"""Returns a flag denoting if the response had any html attributions."""
return (False if self._details is None else
len(self.html_attributions) > 0)
def checkin(self):
"""Checks in an anonymous user in."""
self._query_instance.checkin(self.place_id,
self._query_instance.sensor)
def get_details(self, language=None):
"""Retrieves full information on the place matching the place_id.
Further attributes will be made available on the instance once this
method has been invoked.
keyword arguments:
language -- The language code, indicating in which language the
results should be returned, if possible. This value defaults
to the language that was used to generate the
GooglePlacesSearchResult instance.
"""
if self._details is None:
if language is None:
try:
language = self._query_instance._request_params['language']
except KeyError:
language = lang.ENGLISH
self._details = _get_place_details(
self.place_id, self._query_instance.api_key,
self._query_instance.sensor, language=language)
@cached_property
def photos(self):
self.get_details()
return [Photo(self._query_instance, i)
for i in self.details.get('photos', [])]
def _validate_status(self):
if self._details is None:
error_detail = ('The attribute requested is only available after ' +
'an explicit call to get_details() is made.')
raise GooglePlacesAttributeError(error_detail)
def __repr__(self):
""" Return a string representation including the name, lat, and lng. """
return '<{} name="{}", lat={}, lng={}>'.format(
self.__class__.__name__,
self.name,
self.geo_location['lat'],
self.geo_location['lng']
)
|
slimkrazy/python-google-places | googleplaces/__init__.py | Place.vicinity | python | def vicinity(self):
if self._vicinity == '' and self.details != None and 'vicinity' in self.details:
self._vicinity = self.details['vicinity']
return self._vicinity | Returns a feature name of a nearby location.
Often this feature refers to a street or neighborhood within the given
results. | train | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L922-L930 | null | class Place(object):
"""
Represents a place from the results of a Google Places API query.
"""
def __init__(self, query_instance, place_data):
self._query_instance = query_instance
self._place_id = place_data['place_id']
self._id = place_data.get('id', '')
self._reference = place_data.get('reference', '')
self._name = place_data.get('name','')
self._vicinity = place_data.get('vicinity', '')
self._geo_location = place_data['geometry']['location']
self._rating = place_data.get('rating','')
self._types = place_data.get('types','')
self._icon = place_data.get('icon','')
if place_data.get('address_components') is None:
self._details = None
else:
self._details = place_data
@property
def reference(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns contains a unique token for the place.
The token can be used to retrieve additional information about this
place when invoking the getPlace method on an GooglePlaces instance.
You can store this token and use it at any time in future to refresh
cached data about this Place, but the same token is not guaranteed to
be returned for any given Place across different searches."""
warnings.warn('The "reference" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._reference
@property
def id(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns the unique stable identifier denoting this place.
This identifier may not be used to retrieve information about this
place, but is guaranteed to be valid across sessions. It can be used
to consolidate data about this Place, and to verify the identity of a
Place across separate searches.
"""
warnings.warn('The "id" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._id
@property
def place_id(self):
"""Returns the unique stable identifier denoting this place.
This identifier may be used to retrieve information about this
place.
This should be considered the primary identifier of a place.
"""
return self._place_id
@property
def icon(self):
"""Returns the URL of a recommended icon for display."""
if self._icon == '' and self.details != None and 'icon' in self.details:
self._icon = self.details['icon']
return self._icon
@property
def types(self):
"""Returns a list of feature types describing the given result."""
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types
@property
def geo_location(self):
"""Returns the lat lng co-ordinates of the place.
A dict with the keys 'lat' and 'lng' will be returned.
"""
return self._geo_location
@property
def name(self):
"""Returns the human-readable name of the place."""
if self._name == '' and self.details != None and 'name' in self.details:
self._name = self.details['name']
return self._name
@property
@property
def rating(self):
"""Returns the Place's rating, from 0.0 to 5.0, based on user reviews.
This method will return None for places that have no rating.
"""
if self._rating == '' and self.details != None and 'rating' in self.details:
self._rating = self.details['rating']
return self._rating
# The following properties require a further API call in order to be
# available.
@property
def details(self):
"""Returns the JSON response from Google Places Detail search API."""
self._validate_status()
return self._details
@property
def formatted_address(self):
"""Returns a string containing the human-readable address of this place.
Often this address is equivalent to the "postal address," which
sometimes differs from country to country. (Note that some countries,
such as the United Kingdom, do not allow distribution of complete postal
addresses due to licensing restrictions.)
"""
self._validate_status()
return self.details.get('formatted_address')
@property
def local_phone_number(self):
"""Returns the Place's phone number in its local format."""
self._validate_status()
return self.details.get('formatted_phone_number')
@property
def international_phone_number(self):
self._validate_status()
return self.details.get('international_phone_number')
@property
def website(self):
"""Returns the authoritative website for this Place."""
self._validate_status()
return self.details.get('website')
@property
def url(self):
"""Contains the official Google Place Page URL of this establishment.
Applications must link to or embed the Google Place page on any screen
that shows detailed results about this Place to the user.
"""
self._validate_status()
return self.details.get('url')
@property
def html_attributions(self):
"""Returns the HTML attributions for the specified response.
Any returned HTML attributions MUST be displayed as-is, in accordance
with the requirements as found in the documentation. Please see the
module comments for links to the relevant url.
"""
self._validate_status()
return self.details.get('html_attributions', [])
@property
def has_attributions(self):
"""Returns a flag denoting if the response had any html attributions."""
return (False if self._details is None else
len(self.html_attributions) > 0)
def checkin(self):
"""Checks in an anonymous user in."""
self._query_instance.checkin(self.place_id,
self._query_instance.sensor)
def get_details(self, language=None):
"""Retrieves full information on the place matching the place_id.
Further attributes will be made available on the instance once this
method has been invoked.
keyword arguments:
language -- The language code, indicating in which language the
results should be returned, if possible. This value defaults
to the language that was used to generate the
GooglePlacesSearchResult instance.
"""
if self._details is None:
if language is None:
try:
language = self._query_instance._request_params['language']
except KeyError:
language = lang.ENGLISH
self._details = _get_place_details(
self.place_id, self._query_instance.api_key,
self._query_instance.sensor, language=language)
@cached_property
def photos(self):
self.get_details()
return [Photo(self._query_instance, i)
for i in self.details.get('photos', [])]
def _validate_status(self):
if self._details is None:
error_detail = ('The attribute requested is only available after ' +
'an explicit call to get_details() is made.')
raise GooglePlacesAttributeError(error_detail)
def __repr__(self):
""" Return a string representation including the name, lat, and lng. """
return '<{} name="{}", lat={}, lng={}>'.format(
self.__class__.__name__,
self.name,
self.geo_location['lat'],
self.geo_location['lng']
)
|
slimkrazy/python-google-places | googleplaces/__init__.py | Place.rating | python | def rating(self):
if self._rating == '' and self.details != None and 'rating' in self.details:
self._rating = self.details['rating']
return self._rating | Returns the Place's rating, from 0.0 to 5.0, based on user reviews.
This method will return None for places that have no rating. | train | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L933-L940 | null | class Place(object):
"""
Represents a place from the results of a Google Places API query.
"""
def __init__(self, query_instance, place_data):
self._query_instance = query_instance
self._place_id = place_data['place_id']
self._id = place_data.get('id', '')
self._reference = place_data.get('reference', '')
self._name = place_data.get('name','')
self._vicinity = place_data.get('vicinity', '')
self._geo_location = place_data['geometry']['location']
self._rating = place_data.get('rating','')
self._types = place_data.get('types','')
self._icon = place_data.get('icon','')
if place_data.get('address_components') is None:
self._details = None
else:
self._details = place_data
@property
def reference(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns contains a unique token for the place.
The token can be used to retrieve additional information about this
place when invoking the getPlace method on an GooglePlaces instance.
You can store this token and use it at any time in future to refresh
cached data about this Place, but the same token is not guaranteed to
be returned for any given Place across different searches."""
warnings.warn('The "reference" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._reference
@property
def id(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns the unique stable identifier denoting this place.
This identifier may not be used to retrieve information about this
place, but is guaranteed to be valid across sessions. It can be used
to consolidate data about this Place, and to verify the identity of a
Place across separate searches.
"""
warnings.warn('The "id" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._id
@property
def place_id(self):
"""Returns the unique stable identifier denoting this place.
This identifier may be used to retrieve information about this
place.
This should be considered the primary identifier of a place.
"""
return self._place_id
@property
def icon(self):
"""Returns the URL of a recommended icon for display."""
if self._icon == '' and self.details != None and 'icon' in self.details:
self._icon = self.details['icon']
return self._icon
@property
def types(self):
"""Returns a list of feature types describing the given result."""
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types
@property
def geo_location(self):
"""Returns the lat lng co-ordinates of the place.
A dict with the keys 'lat' and 'lng' will be returned.
"""
return self._geo_location
@property
def name(self):
"""Returns the human-readable name of the place."""
if self._name == '' and self.details != None and 'name' in self.details:
self._name = self.details['name']
return self._name
@property
def vicinity(self):
"""Returns a feature name of a nearby location.
Often this feature refers to a street or neighborhood within the given
results.
"""
if self._vicinity == '' and self.details != None and 'vicinity' in self.details:
self._vicinity = self.details['vicinity']
return self._vicinity
@property
# The following properties require a further API call in order to be
# available.
@property
def details(self):
"""Returns the JSON response from Google Places Detail search API."""
self._validate_status()
return self._details
@property
def formatted_address(self):
"""Returns a string containing the human-readable address of this place.
Often this address is equivalent to the "postal address," which
sometimes differs from country to country. (Note that some countries,
such as the United Kingdom, do not allow distribution of complete postal
addresses due to licensing restrictions.)
"""
self._validate_status()
return self.details.get('formatted_address')
@property
def local_phone_number(self):
"""Returns the Place's phone number in its local format."""
self._validate_status()
return self.details.get('formatted_phone_number')
@property
def international_phone_number(self):
self._validate_status()
return self.details.get('international_phone_number')
@property
def website(self):
"""Returns the authoritative website for this Place."""
self._validate_status()
return self.details.get('website')
@property
def url(self):
"""Contains the official Google Place Page URL of this establishment.
Applications must link to or embed the Google Place page on any screen
that shows detailed results about this Place to the user.
"""
self._validate_status()
return self.details.get('url')
@property
def html_attributions(self):
"""Returns the HTML attributions for the specified response.
Any returned HTML attributions MUST be displayed as-is, in accordance
with the requirements as found in the documentation. Please see the
module comments for links to the relevant url.
"""
self._validate_status()
return self.details.get('html_attributions', [])
@property
def has_attributions(self):
"""Returns a flag denoting if the response had any html attributions."""
return (False if self._details is None else
len(self.html_attributions) > 0)
def checkin(self):
"""Checks in an anonymous user in."""
self._query_instance.checkin(self.place_id,
self._query_instance.sensor)
def get_details(self, language=None):
"""Retrieves full information on the place matching the place_id.
Further attributes will be made available on the instance once this
method has been invoked.
keyword arguments:
language -- The language code, indicating in which language the
results should be returned, if possible. This value defaults
to the language that was used to generate the
GooglePlacesSearchResult instance.
"""
if self._details is None:
if language is None:
try:
language = self._query_instance._request_params['language']
except KeyError:
language = lang.ENGLISH
self._details = _get_place_details(
self.place_id, self._query_instance.api_key,
self._query_instance.sensor, language=language)
@cached_property
def photos(self):
self.get_details()
return [Photo(self._query_instance, i)
for i in self.details.get('photos', [])]
def _validate_status(self):
if self._details is None:
error_detail = ('The attribute requested is only available after ' +
'an explicit call to get_details() is made.')
raise GooglePlacesAttributeError(error_detail)
def __repr__(self):
""" Return a string representation including the name, lat, and lng. """
return '<{} name="{}", lat={}, lng={}>'.format(
self.__class__.__name__,
self.name,
self.geo_location['lat'],
self.geo_location['lng']
)
|
slimkrazy/python-google-places | googleplaces/__init__.py | Place.checkin | python | def checkin(self):
self._query_instance.checkin(self.place_id,
self._query_instance.sensor) | Checks in an anonymous user in. | train | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L1006-L1009 | null | class Place(object):
"""
Represents a place from the results of a Google Places API query.
"""
def __init__(self, query_instance, place_data):
self._query_instance = query_instance
self._place_id = place_data['place_id']
self._id = place_data.get('id', '')
self._reference = place_data.get('reference', '')
self._name = place_data.get('name','')
self._vicinity = place_data.get('vicinity', '')
self._geo_location = place_data['geometry']['location']
self._rating = place_data.get('rating','')
self._types = place_data.get('types','')
self._icon = place_data.get('icon','')
if place_data.get('address_components') is None:
self._details = None
else:
self._details = place_data
@property
def reference(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns contains a unique token for the place.
The token can be used to retrieve additional information about this
place when invoking the getPlace method on an GooglePlaces instance.
You can store this token and use it at any time in future to refresh
cached data about this Place, but the same token is not guaranteed to
be returned for any given Place across different searches."""
warnings.warn('The "reference" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._reference
@property
def id(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns the unique stable identifier denoting this place.
This identifier may not be used to retrieve information about this
place, but is guaranteed to be valid across sessions. It can be used
to consolidate data about this Place, and to verify the identity of a
Place across separate searches.
"""
warnings.warn('The "id" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._id
@property
def place_id(self):
"""Returns the unique stable identifier denoting this place.
This identifier may be used to retrieve information about this
place.
This should be considered the primary identifier of a place.
"""
return self._place_id
@property
def icon(self):
"""Returns the URL of a recommended icon for display."""
if self._icon == '' and self.details != None and 'icon' in self.details:
self._icon = self.details['icon']
return self._icon
@property
def types(self):
"""Returns a list of feature types describing the given result."""
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types
@property
def geo_location(self):
"""Returns the lat lng co-ordinates of the place.
A dict with the keys 'lat' and 'lng' will be returned.
"""
return self._geo_location
@property
def name(self):
"""Returns the human-readable name of the place."""
if self._name == '' and self.details != None and 'name' in self.details:
self._name = self.details['name']
return self._name
@property
def vicinity(self):
"""Returns a feature name of a nearby location.
Often this feature refers to a street or neighborhood within the given
results.
"""
if self._vicinity == '' and self.details != None and 'vicinity' in self.details:
self._vicinity = self.details['vicinity']
return self._vicinity
@property
def rating(self):
"""Returns the Place's rating, from 0.0 to 5.0, based on user reviews.
This method will return None for places that have no rating.
"""
if self._rating == '' and self.details != None and 'rating' in self.details:
self._rating = self.details['rating']
return self._rating
# The following properties require a further API call in order to be
# available.
@property
def details(self):
"""Returns the JSON response from Google Places Detail search API."""
self._validate_status()
return self._details
@property
def formatted_address(self):
"""Returns a string containing the human-readable address of this place.
Often this address is equivalent to the "postal address," which
sometimes differs from country to country. (Note that some countries,
such as the United Kingdom, do not allow distribution of complete postal
addresses due to licensing restrictions.)
"""
self._validate_status()
return self.details.get('formatted_address')
@property
def local_phone_number(self):
"""Returns the Place's phone number in its local format."""
self._validate_status()
return self.details.get('formatted_phone_number')
@property
def international_phone_number(self):
self._validate_status()
return self.details.get('international_phone_number')
@property
def website(self):
"""Returns the authoritative website for this Place."""
self._validate_status()
return self.details.get('website')
@property
def url(self):
"""Contains the official Google Place Page URL of this establishment.
Applications must link to or embed the Google Place page on any screen
that shows detailed results about this Place to the user.
"""
self._validate_status()
return self.details.get('url')
@property
def html_attributions(self):
"""Returns the HTML attributions for the specified response.
Any returned HTML attributions MUST be displayed as-is, in accordance
with the requirements as found in the documentation. Please see the
module comments for links to the relevant url.
"""
self._validate_status()
return self.details.get('html_attributions', [])
@property
def has_attributions(self):
"""Returns a flag denoting if the response had any html attributions."""
return (False if self._details is None else
len(self.html_attributions) > 0)
def get_details(self, language=None):
"""Retrieves full information on the place matching the place_id.
Further attributes will be made available on the instance once this
method has been invoked.
keyword arguments:
language -- The language code, indicating in which language the
results should be returned, if possible. This value defaults
to the language that was used to generate the
GooglePlacesSearchResult instance.
"""
if self._details is None:
if language is None:
try:
language = self._query_instance._request_params['language']
except KeyError:
language = lang.ENGLISH
self._details = _get_place_details(
self.place_id, self._query_instance.api_key,
self._query_instance.sensor, language=language)
@cached_property
def photos(self):
self.get_details()
return [Photo(self._query_instance, i)
for i in self.details.get('photos', [])]
def _validate_status(self):
if self._details is None:
error_detail = ('The attribute requested is only available after ' +
'an explicit call to get_details() is made.')
raise GooglePlacesAttributeError(error_detail)
def __repr__(self):
""" Return a string representation including the name, lat, and lng. """
return '<{} name="{}", lat={}, lng={}>'.format(
self.__class__.__name__,
self.name,
self.geo_location['lat'],
self.geo_location['lng']
)
|
slimkrazy/python-google-places | googleplaces/__init__.py | Place.get_details | python | def get_details(self, language=None):
if self._details is None:
if language is None:
try:
language = self._query_instance._request_params['language']
except KeyError:
language = lang.ENGLISH
self._details = _get_place_details(
self.place_id, self._query_instance.api_key,
self._query_instance.sensor, language=language) | Retrieves full information on the place matching the place_id.
Further attributes will be made available on the instance once this
method has been invoked.
keyword arguments:
language -- The language code, indicating in which language the
results should be returned, if possible. This value defaults
to the language that was used to generate the
GooglePlacesSearchResult instance. | train | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L1011-L1031 | [
"def _get_place_details(place_id, api_key, sensor=False,\n language=lang.ENGLISH):\n \"\"\"Gets a detailed place response.\n\n keyword arguments:\n place_id -- The unique identifier for the required place.\n \"\"\"\n url, detail_response = _fetch_remote_json(GooglePlaces.DETAIL_... | class Place(object):
"""
Represents a place from the results of a Google Places API query.
"""
def __init__(self, query_instance, place_data):
self._query_instance = query_instance
self._place_id = place_data['place_id']
self._id = place_data.get('id', '')
self._reference = place_data.get('reference', '')
self._name = place_data.get('name','')
self._vicinity = place_data.get('vicinity', '')
self._geo_location = place_data['geometry']['location']
self._rating = place_data.get('rating','')
self._types = place_data.get('types','')
self._icon = place_data.get('icon','')
if place_data.get('address_components') is None:
self._details = None
else:
self._details = place_data
@property
def reference(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns contains a unique token for the place.
The token can be used to retrieve additional information about this
place when invoking the getPlace method on an GooglePlaces instance.
You can store this token and use it at any time in future to refresh
cached data about this Place, but the same token is not guaranteed to
be returned for any given Place across different searches."""
warnings.warn('The "reference" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._reference
@property
def id(self):
"""DEPRECATED AS OF JUNE 24, 2014. May stop being returned on June 24,
2015. Reference: https://developers.google.com/places/documentation/search
Returns the unique stable identifier denoting this place.
This identifier may not be used to retrieve information about this
place, but is guaranteed to be valid across sessions. It can be used
to consolidate data about this Place, and to verify the identity of a
Place across separate searches.
"""
warnings.warn('The "id" feature is deprecated and may'
'stop working any time after June 24, 2015.',
FutureWarning)
return self._id
@property
def place_id(self):
"""Returns the unique stable identifier denoting this place.
This identifier may be used to retrieve information about this
place.
This should be considered the primary identifier of a place.
"""
return self._place_id
@property
def icon(self):
"""Returns the URL of a recommended icon for display."""
if self._icon == '' and self.details != None and 'icon' in self.details:
self._icon = self.details['icon']
return self._icon
@property
def types(self):
"""Returns a list of feature types describing the given result."""
if self._types == '' and self.details != None and 'types' in self.details:
self._icon = self.details['types']
return self._types
@property
def geo_location(self):
"""Returns the lat lng co-ordinates of the place.
A dict with the keys 'lat' and 'lng' will be returned.
"""
return self._geo_location
@property
def name(self):
"""Returns the human-readable name of the place."""
if self._name == '' and self.details != None and 'name' in self.details:
self._name = self.details['name']
return self._name
@property
def vicinity(self):
"""Returns a feature name of a nearby location.
Often this feature refers to a street or neighborhood within the given
results.
"""
if self._vicinity == '' and self.details != None and 'vicinity' in self.details:
self._vicinity = self.details['vicinity']
return self._vicinity
@property
def rating(self):
"""Returns the Place's rating, from 0.0 to 5.0, based on user reviews.
This method will return None for places that have no rating.
"""
if self._rating == '' and self.details != None and 'rating' in self.details:
self._rating = self.details['rating']
return self._rating
# The following properties require a further API call in order to be
# available.
@property
def details(self):
"""Returns the JSON response from Google Places Detail search API."""
self._validate_status()
return self._details
@property
def formatted_address(self):
"""Returns a string containing the human-readable address of this place.
Often this address is equivalent to the "postal address," which
sometimes differs from country to country. (Note that some countries,
such as the United Kingdom, do not allow distribution of complete postal
addresses due to licensing restrictions.)
"""
self._validate_status()
return self.details.get('formatted_address')
@property
def local_phone_number(self):
"""Returns the Place's phone number in its local format."""
self._validate_status()
return self.details.get('formatted_phone_number')
@property
def international_phone_number(self):
self._validate_status()
return self.details.get('international_phone_number')
@property
def website(self):
"""Returns the authoritative website for this Place."""
self._validate_status()
return self.details.get('website')
@property
def url(self):
"""Contains the official Google Place Page URL of this establishment.
Applications must link to or embed the Google Place page on any screen
that shows detailed results about this Place to the user.
"""
self._validate_status()
return self.details.get('url')
@property
def html_attributions(self):
"""Returns the HTML attributions for the specified response.
Any returned HTML attributions MUST be displayed as-is, in accordance
with the requirements as found in the documentation. Please see the
module comments for links to the relevant url.
"""
self._validate_status()
return self.details.get('html_attributions', [])
@property
def has_attributions(self):
"""Returns a flag denoting if the response had any html attributions."""
return (False if self._details is None else
len(self.html_attributions) > 0)
def checkin(self):
"""Checks in an anonymous user in."""
self._query_instance.checkin(self.place_id,
self._query_instance.sensor)
@cached_property
def photos(self):
self.get_details()
return [Photo(self._query_instance, i)
for i in self.details.get('photos', [])]
def _validate_status(self):
if self._details is None:
error_detail = ('The attribute requested is only available after ' +
'an explicit call to get_details() is made.')
raise GooglePlacesAttributeError(error_detail)
def __repr__(self):
""" Return a string representation including the name, lat, and lng. """
return '<{} name="{}", lat={}, lng={}>'.format(
self.__class__.__name__,
self.name,
self.geo_location['lat'],
self.geo_location['lng']
)
|
slimkrazy/python-google-places | googleplaces/__init__.py | Photo.get | python | def get(self, maxheight=None, maxwidth=None, sensor=False):
if not maxheight and not maxwidth:
raise GooglePlacesError('You must specify maxheight or maxwidth!')
result = _get_place_photo(self.photo_reference,
self._query_instance.api_key,
maxheight=maxheight, maxwidth=maxwidth,
sensor=sensor)
self.mimetype, self.filename, self.data, self.url = result | Fetch photo from API. | train | https://github.com/slimkrazy/python-google-places/blob/d4b7363e1655cdc091a6253379f6d2a95b827881/googleplaces/__init__.py#L1063-L1073 | [
"def _get_place_photo(photoreference, api_key, maxheight=None, maxwidth=None,\n sensor=False):\n \"\"\"Gets a place's photo by reference.\n See detailed documentation at https://developers.google.com/places/documentation/photos\n\n Arguments:\n photoreference -- The unique Google r... | class Photo(object):
def __init__(self, query_instance, attrs):
self._query_instance = query_instance
self.orig_height = attrs.get('height')
self.orig_width = attrs.get('width')
self.html_attributions = attrs.get('html_attributions')
self.photo_reference = attrs.get('photo_reference')
|
toidi/hadoop-yarn-api-python-client | yarn_api_client/node_manager.py | NodeManager.node_applications | python | def node_applications(self, state=None, user=None):
path = '/ws/v1/node/apps'
legal_states = set([s for s, _ in ApplicationState])
if state is not None and state not in legal_states:
msg = 'Application State %s is illegal' % (state,)
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('user', user))
params = self.construct_parameters(loc_args)
return self.request(path, **params) | With the Applications API, you can obtain a collection of resources,
each of which represents an application.
:param str state: application state
:param str user: user name
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `state`
incorrect | train | https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/node_manager.py#L31-L56 | [
"def request(self, api_path, **query_args):\n params = query_args\n api_endpoint = 'http://{}:{}{}'.format(self.address, self.port, api_path)\n\n self.logger.info('API Endpoint {}'.format(api_endpoint))\n\n self._validate_configuration()\n\n response = None\n if self.kerberos_enabled:\n fro... | class NodeManager(BaseYarnAPI):
"""
The NodeManager REST API's allow the user to get status on the node and
information about applications and containers running on that node.
:param str address: NodeManager HTTP address
:param int port: NodeManager HTTP port
:param int timeout: API connection timeout in seconds
:param boolean kerberos_enabled: Flag identifying is Kerberos Security has been enabled for YARN
"""
def __init__(self, address=None, port=8042, timeout=30, kerberos_enabled=False):
self.address, self.port, self.timeout, self.kerberos_enabled = address, port, timeout, kerberos_enabled
def node_information(self):
"""
The node information resource provides overall information about that
particular node.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/node/info'
return self.request(path)
def node_application(self, application_id):
"""
An application resource contains information about a particular
application that was run or is running on this NodeManager.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/node/apps/{appid}'.format(appid=application_id)
return self.request(path)
def node_containers(self):
"""
With the containers API, you can obtain a collection of resources,
each of which represents a container.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/node/containers'
return self.request(path)
def node_container(self, container_id):
"""
A container resource contains information about a particular container
that is running on this NodeManager.
:param str container_id: The container id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/node/containers/{containerid}'.format(
containerid=container_id)
return self.request(path)
|
toidi/hadoop-yarn-api-python-client | yarn_api_client/node_manager.py | NodeManager.node_application | python | def node_application(self, application_id):
path = '/ws/v1/node/apps/{appid}'.format(appid=application_id)
return self.request(path) | An application resource contains information about a particular
application that was run or is running on this NodeManager.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response` | train | https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/node_manager.py#L58-L69 | [
"def request(self, api_path, **query_args):\n params = query_args\n api_endpoint = 'http://{}:{}{}'.format(self.address, self.port, api_path)\n\n self.logger.info('API Endpoint {}'.format(api_endpoint))\n\n self._validate_configuration()\n\n response = None\n if self.kerberos_enabled:\n fro... | class NodeManager(BaseYarnAPI):
"""
The NodeManager REST API's allow the user to get status on the node and
information about applications and containers running on that node.
:param str address: NodeManager HTTP address
:param int port: NodeManager HTTP port
:param int timeout: API connection timeout in seconds
:param boolean kerberos_enabled: Flag identifying is Kerberos Security has been enabled for YARN
"""
def __init__(self, address=None, port=8042, timeout=30, kerberos_enabled=False):
self.address, self.port, self.timeout, self.kerberos_enabled = address, port, timeout, kerberos_enabled
def node_information(self):
"""
The node information resource provides overall information about that
particular node.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/node/info'
return self.request(path)
def node_applications(self, state=None, user=None):
"""
With the Applications API, you can obtain a collection of resources,
each of which represents an application.
:param str state: application state
:param str user: user name
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `state`
incorrect
"""
path = '/ws/v1/node/apps'
legal_states = set([s for s, _ in ApplicationState])
if state is not None and state not in legal_states:
msg = 'Application State %s is illegal' % (state,)
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('user', user))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def node_containers(self):
"""
With the containers API, you can obtain a collection of resources,
each of which represents a container.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/node/containers'
return self.request(path)
def node_container(self, container_id):
"""
A container resource contains information about a particular container
that is running on this NodeManager.
:param str container_id: The container id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/node/containers/{containerid}'.format(
containerid=container_id)
return self.request(path)
|
toidi/hadoop-yarn-api-python-client | yarn_api_client/node_manager.py | NodeManager.node_container | python | def node_container(self, container_id):
path = '/ws/v1/node/containers/{containerid}'.format(
containerid=container_id)
return self.request(path) | A container resource contains information about a particular container
that is running on this NodeManager.
:param str container_id: The container id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response` | train | https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/node_manager.py#L83-L95 | [
"def request(self, api_path, **query_args):\n params = query_args\n api_endpoint = 'http://{}:{}{}'.format(self.address, self.port, api_path)\n\n self.logger.info('API Endpoint {}'.format(api_endpoint))\n\n self._validate_configuration()\n\n response = None\n if self.kerberos_enabled:\n fro... | class NodeManager(BaseYarnAPI):
"""
The NodeManager REST API's allow the user to get status on the node and
information about applications and containers running on that node.
:param str address: NodeManager HTTP address
:param int port: NodeManager HTTP port
:param int timeout: API connection timeout in seconds
:param boolean kerberos_enabled: Flag identifying is Kerberos Security has been enabled for YARN
"""
def __init__(self, address=None, port=8042, timeout=30, kerberos_enabled=False):
self.address, self.port, self.timeout, self.kerberos_enabled = address, port, timeout, kerberos_enabled
def node_information(self):
"""
The node information resource provides overall information about that
particular node.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/node/info'
return self.request(path)
def node_applications(self, state=None, user=None):
"""
With the Applications API, you can obtain a collection of resources,
each of which represents an application.
:param str state: application state
:param str user: user name
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `state`
incorrect
"""
path = '/ws/v1/node/apps'
legal_states = set([s for s, _ in ApplicationState])
if state is not None and state not in legal_states:
msg = 'Application State %s is illegal' % (state,)
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('user', user))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def node_application(self, application_id):
"""
An application resource contains information about a particular
application that was run or is running on this NodeManager.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/node/apps/{appid}'.format(appid=application_id)
return self.request(path)
def node_containers(self):
"""
With the containers API, you can obtain a collection of resources,
each of which represents a container.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/node/containers'
return self.request(path)
|
toidi/hadoop-yarn-api-python-client | yarn_api_client/resource_manager.py | ResourceManager.cluster_applications | python | def cluster_applications(self, state=None, final_status=None,
user=None, queue=None, limit=None,
started_time_begin=None, started_time_end=None,
finished_time_begin=None, finished_time_end=None):
path = '/ws/v1/cluster/apps'
legal_states = set([s for s, _ in YarnApplicationState])
if state is not None and state not in legal_states:
msg = 'Yarn Application State %s is illegal' % (state,)
raise IllegalArgumentError(msg)
legal_final_statuses = set([s for s, _ in FinalApplicationStatus])
if final_status is not None and final_status not in legal_final_statuses:
msg = 'Final Application Status %s is illegal' % (final_status,)
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('finalStatus', final_status),
('user', user),
('queue', queue),
('limit', limit),
('startedTimeBegin', started_time_begin),
('startedTimeEnd', started_time_end),
('finishedTimeBegin', finished_time_begin),
('finishedTimeEnd', finished_time_end))
params = self.construct_parameters(loc_args)
return self.request(path, **params) | With the Applications API, you can obtain a collection of resources,
each of which represents an application.
:param str state: state of the application
:param str final_status: the final status of the
application - reported by the application itself
:param str user: user name
:param str queue: queue name
:param str limit: total number of app objects to be returned
:param str started_time_begin: applications with start time beginning
with this time, specified in ms since epoch
:param str started_time_end: applications with start time ending with
this time, specified in ms since epoch
:param str finished_time_begin: applications with finish time
beginning with this time, specified in ms since epoch
:param str finished_time_end: applications with finish time ending
with this time, specified in ms since epoch
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `state` or
`final_status` incorrect | train | https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/resource_manager.py#L68-L120 | [
"def request(self, api_path, **query_args):\n params = query_args\n api_endpoint = 'http://{}:{}{}'.format(self.address, self.port, api_path)\n\n self.logger.info('API Endpoint {}'.format(api_endpoint))\n\n self._validate_configuration()\n\n response = None\n if self.kerberos_enabled:\n fro... | class ResourceManager(BaseYarnAPI):
"""
The ResourceManager REST API's allow the user to get information about the
cluster - status on the cluster, metrics on the cluster,
scheduler information, information about nodes in the cluster,
and information about applications on the cluster.
If `address` argument is `None` client will try to extract `address` and
`port` from Hadoop configuration files.
:param str address: ResourceManager HTTP address
:param int port: ResourceManager HTTP port
:param int timeout: API connection timeout in seconds
:param boolean kerberos_enabled: Flag identifying is Kerberos Security has been enabled for YARN
"""
def __init__(self, address=None, port=8088, timeout=30, kerberos_enabled=False):
self.address, self.port, self.timeout, self.kerberos_enabled = address, port, timeout, kerberos_enabled
if address is None:
self.logger.debug('Get configuration from hadoop conf dir')
address, port = get_resource_manager_host_port()
self.address, self.port = address, port
def cluster_information(self):
"""
The cluster information resource provides overall information about
the cluster.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/info'
return self.request(path)
def cluster_metrics(self):
"""
The cluster metrics resource provides some overall metrics about the
cluster. More detailed metrics should be retrieved from the jmx
interface.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/metrics'
return self.request(path)
def cluster_scheduler(self):
"""
A scheduler resource contains information about the current scheduler
configured in a cluster. It currently supports both the Fifo and
Capacity Scheduler. You will get different information depending on
which scheduler is configured so be sure to look at the type
information.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/scheduler'
return self.request(path)
def cluster_application_statistics(self, state_list=None,
application_type_list=None):
"""
With the Application Statistics API, you can obtain a collection of
triples, each of which contains the application type, the application
state and the number of applications of this type and this state in
ResourceManager context.
This method work in Hadoop > 2.0.0
:param list state_list: states of the applications, specified as a
comma-separated list. If states is not provided, the API will
enumerate all application states and return the counts of them.
:param list application_type_list: types of the applications,
specified as a comma-separated list. If application_types is not
provided, the API will count the applications of any application
type. In this case, the response shows * to indicate any
application type. Note that we only support at most one
applicationType temporarily. Otherwise, users will expect
an BadRequestException.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/appstatistics'
# TODO: validate state argument
states = ','.join(state_list) if state_list is not None else None
if application_type_list is not None:
application_types = ','.join(application_type_list)
else:
application_types = None
loc_args = (
('states', states),
('applicationTypes', application_types))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def cluster_application(self, application_id):
"""
An application resource contains information about a particular
application that was submitted to a cluster.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}'.format(appid=application_id)
return self.request(path)
def cluster_application_attempts(self, application_id):
"""
With the application attempts API, you can obtain a collection of
resources that represent an application attempt.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts'.format(
appid=application_id)
return self.request(path)
def cluster_application_attempt_info(self, application_id, attempt_id):
"""
With the application attempts API, you can obtain an extended info about
an application attempt.
:param str application_id: The application id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts/{attemptid}'.format(
appid=application_id, attemptid=attempt_id)
return self.request(path)
def cluster_application_attempt_containers(self, application_id, attempt_id):
"""
With the application attempts API, you can obtain an information
about container related to an application attempt.
:param str application_id: The application id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts/{attemptid}/containers'.format(
appid=application_id, attemptid=attempt_id)
return self.request(path)
def cluster_application_state(self, application_id):
"""
With the application state API, you can obtain the current
state of an application.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/state'.format(
appid=application_id)
return self.request(path)
def cluster_application_kill(self, application_id):
"""
With the application kill API, you can kill an application
that is not in FINISHED or FAILED state.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
data = '{"state": "KILLED"}'
path = '/ws/v1/cluster/apps/{appid}/state'.format(
appid=application_id)
return self.update(path, data)
def cluster_nodes(self, state=None, healthy=None):
"""
With the Nodes API, you can obtain a collection of resources, each of
which represents a node.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `healthy`
incorrect
"""
path = '/ws/v1/cluster/nodes'
# TODO: validate state argument
legal_healthy = ['true', 'false']
if healthy is not None and healthy not in legal_healthy:
msg = 'Valid Healthy arguments are true, false'
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('healthy', healthy),
)
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def cluster_node(self, node_id):
"""
A node resource contains information about a node in the cluster.
:param str node_id: The node id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/nodes/{nodeid}'.format(nodeid=node_id)
return self.request(path)
|
toidi/hadoop-yarn-api-python-client | yarn_api_client/resource_manager.py | ResourceManager.cluster_application_statistics | python | def cluster_application_statistics(self, state_list=None,
application_type_list=None):
path = '/ws/v1/cluster/appstatistics'
# TODO: validate state argument
states = ','.join(state_list) if state_list is not None else None
if application_type_list is not None:
application_types = ','.join(application_type_list)
else:
application_types = None
loc_args = (
('states', states),
('applicationTypes', application_types))
params = self.construct_parameters(loc_args)
return self.request(path, **params) | With the Application Statistics API, you can obtain a collection of
triples, each of which contains the application type, the application
state and the number of applications of this type and this state in
ResourceManager context.
This method work in Hadoop > 2.0.0
:param list state_list: states of the applications, specified as a
comma-separated list. If states is not provided, the API will
enumerate all application states and return the counts of them.
:param list application_type_list: types of the applications,
specified as a comma-separated list. If application_types is not
provided, the API will count the applications of any application
type. In this case, the response shows * to indicate any
application type. Note that we only support at most one
applicationType temporarily. Otherwise, users will expect
an BadRequestException.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response` | train | https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/resource_manager.py#L122-L159 | [
"def request(self, api_path, **query_args):\n params = query_args\n api_endpoint = 'http://{}:{}{}'.format(self.address, self.port, api_path)\n\n self.logger.info('API Endpoint {}'.format(api_endpoint))\n\n self._validate_configuration()\n\n response = None\n if self.kerberos_enabled:\n fro... | class ResourceManager(BaseYarnAPI):
"""
The ResourceManager REST API's allow the user to get information about the
cluster - status on the cluster, metrics on the cluster,
scheduler information, information about nodes in the cluster,
and information about applications on the cluster.
If `address` argument is `None` client will try to extract `address` and
`port` from Hadoop configuration files.
:param str address: ResourceManager HTTP address
:param int port: ResourceManager HTTP port
:param int timeout: API connection timeout in seconds
:param boolean kerberos_enabled: Flag identifying is Kerberos Security has been enabled for YARN
"""
def __init__(self, address=None, port=8088, timeout=30, kerberos_enabled=False):
self.address, self.port, self.timeout, self.kerberos_enabled = address, port, timeout, kerberos_enabled
if address is None:
self.logger.debug('Get configuration from hadoop conf dir')
address, port = get_resource_manager_host_port()
self.address, self.port = address, port
def cluster_information(self):
"""
The cluster information resource provides overall information about
the cluster.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/info'
return self.request(path)
def cluster_metrics(self):
"""
The cluster metrics resource provides some overall metrics about the
cluster. More detailed metrics should be retrieved from the jmx
interface.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/metrics'
return self.request(path)
def cluster_scheduler(self):
"""
A scheduler resource contains information about the current scheduler
configured in a cluster. It currently supports both the Fifo and
Capacity Scheduler. You will get different information depending on
which scheduler is configured so be sure to look at the type
information.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/scheduler'
return self.request(path)
def cluster_applications(self, state=None, final_status=None,
user=None, queue=None, limit=None,
started_time_begin=None, started_time_end=None,
finished_time_begin=None, finished_time_end=None):
"""
With the Applications API, you can obtain a collection of resources,
each of which represents an application.
:param str state: state of the application
:param str final_status: the final status of the
application - reported by the application itself
:param str user: user name
:param str queue: queue name
:param str limit: total number of app objects to be returned
:param str started_time_begin: applications with start time beginning
with this time, specified in ms since epoch
:param str started_time_end: applications with start time ending with
this time, specified in ms since epoch
:param str finished_time_begin: applications with finish time
beginning with this time, specified in ms since epoch
:param str finished_time_end: applications with finish time ending
with this time, specified in ms since epoch
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `state` or
`final_status` incorrect
"""
path = '/ws/v1/cluster/apps'
legal_states = set([s for s, _ in YarnApplicationState])
if state is not None and state not in legal_states:
msg = 'Yarn Application State %s is illegal' % (state,)
raise IllegalArgumentError(msg)
legal_final_statuses = set([s for s, _ in FinalApplicationStatus])
if final_status is not None and final_status not in legal_final_statuses:
msg = 'Final Application Status %s is illegal' % (final_status,)
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('finalStatus', final_status),
('user', user),
('queue', queue),
('limit', limit),
('startedTimeBegin', started_time_begin),
('startedTimeEnd', started_time_end),
('finishedTimeBegin', finished_time_begin),
('finishedTimeEnd', finished_time_end))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def cluster_application(self, application_id):
"""
An application resource contains information about a particular
application that was submitted to a cluster.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}'.format(appid=application_id)
return self.request(path)
def cluster_application_attempts(self, application_id):
"""
With the application attempts API, you can obtain a collection of
resources that represent an application attempt.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts'.format(
appid=application_id)
return self.request(path)
def cluster_application_attempt_info(self, application_id, attempt_id):
"""
With the application attempts API, you can obtain an extended info about
an application attempt.
:param str application_id: The application id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts/{attemptid}'.format(
appid=application_id, attemptid=attempt_id)
return self.request(path)
def cluster_application_attempt_containers(self, application_id, attempt_id):
"""
With the application attempts API, you can obtain an information
about container related to an application attempt.
:param str application_id: The application id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts/{attemptid}/containers'.format(
appid=application_id, attemptid=attempt_id)
return self.request(path)
def cluster_application_state(self, application_id):
"""
With the application state API, you can obtain the current
state of an application.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/state'.format(
appid=application_id)
return self.request(path)
def cluster_application_kill(self, application_id):
"""
With the application kill API, you can kill an application
that is not in FINISHED or FAILED state.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
data = '{"state": "KILLED"}'
path = '/ws/v1/cluster/apps/{appid}/state'.format(
appid=application_id)
return self.update(path, data)
def cluster_nodes(self, state=None, healthy=None):
"""
With the Nodes API, you can obtain a collection of resources, each of
which represents a node.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `healthy`
incorrect
"""
path = '/ws/v1/cluster/nodes'
# TODO: validate state argument
legal_healthy = ['true', 'false']
if healthy is not None and healthy not in legal_healthy:
msg = 'Valid Healthy arguments are true, false'
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('healthy', healthy),
)
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def cluster_node(self, node_id):
"""
A node resource contains information about a node in the cluster.
:param str node_id: The node id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/nodes/{nodeid}'.format(nodeid=node_id)
return self.request(path)
|
toidi/hadoop-yarn-api-python-client | yarn_api_client/resource_manager.py | ResourceManager.cluster_application | python | def cluster_application(self, application_id):
path = '/ws/v1/cluster/apps/{appid}'.format(appid=application_id)
return self.request(path) | An application resource contains information about a particular
application that was submitted to a cluster.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response` | train | https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/resource_manager.py#L161-L172 | [
"def request(self, api_path, **query_args):\n params = query_args\n api_endpoint = 'http://{}:{}{}'.format(self.address, self.port, api_path)\n\n self.logger.info('API Endpoint {}'.format(api_endpoint))\n\n self._validate_configuration()\n\n response = None\n if self.kerberos_enabled:\n fro... | class ResourceManager(BaseYarnAPI):
"""
The ResourceManager REST API's allow the user to get information about the
cluster - status on the cluster, metrics on the cluster,
scheduler information, information about nodes in the cluster,
and information about applications on the cluster.
If `address` argument is `None` client will try to extract `address` and
`port` from Hadoop configuration files.
:param str address: ResourceManager HTTP address
:param int port: ResourceManager HTTP port
:param int timeout: API connection timeout in seconds
:param boolean kerberos_enabled: Flag identifying is Kerberos Security has been enabled for YARN
"""
def __init__(self, address=None, port=8088, timeout=30, kerberos_enabled=False):
self.address, self.port, self.timeout, self.kerberos_enabled = address, port, timeout, kerberos_enabled
if address is None:
self.logger.debug('Get configuration from hadoop conf dir')
address, port = get_resource_manager_host_port()
self.address, self.port = address, port
def cluster_information(self):
"""
The cluster information resource provides overall information about
the cluster.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/info'
return self.request(path)
def cluster_metrics(self):
"""
The cluster metrics resource provides some overall metrics about the
cluster. More detailed metrics should be retrieved from the jmx
interface.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/metrics'
return self.request(path)
def cluster_scheduler(self):
"""
A scheduler resource contains information about the current scheduler
configured in a cluster. It currently supports both the Fifo and
Capacity Scheduler. You will get different information depending on
which scheduler is configured so be sure to look at the type
information.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/scheduler'
return self.request(path)
def cluster_applications(self, state=None, final_status=None,
user=None, queue=None, limit=None,
started_time_begin=None, started_time_end=None,
finished_time_begin=None, finished_time_end=None):
"""
With the Applications API, you can obtain a collection of resources,
each of which represents an application.
:param str state: state of the application
:param str final_status: the final status of the
application - reported by the application itself
:param str user: user name
:param str queue: queue name
:param str limit: total number of app objects to be returned
:param str started_time_begin: applications with start time beginning
with this time, specified in ms since epoch
:param str started_time_end: applications with start time ending with
this time, specified in ms since epoch
:param str finished_time_begin: applications with finish time
beginning with this time, specified in ms since epoch
:param str finished_time_end: applications with finish time ending
with this time, specified in ms since epoch
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `state` or
`final_status` incorrect
"""
path = '/ws/v1/cluster/apps'
legal_states = set([s for s, _ in YarnApplicationState])
if state is not None and state not in legal_states:
msg = 'Yarn Application State %s is illegal' % (state,)
raise IllegalArgumentError(msg)
legal_final_statuses = set([s for s, _ in FinalApplicationStatus])
if final_status is not None and final_status not in legal_final_statuses:
msg = 'Final Application Status %s is illegal' % (final_status,)
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('finalStatus', final_status),
('user', user),
('queue', queue),
('limit', limit),
('startedTimeBegin', started_time_begin),
('startedTimeEnd', started_time_end),
('finishedTimeBegin', finished_time_begin),
('finishedTimeEnd', finished_time_end))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def cluster_application_statistics(self, state_list=None,
application_type_list=None):
"""
With the Application Statistics API, you can obtain a collection of
triples, each of which contains the application type, the application
state and the number of applications of this type and this state in
ResourceManager context.
This method work in Hadoop > 2.0.0
:param list state_list: states of the applications, specified as a
comma-separated list. If states is not provided, the API will
enumerate all application states and return the counts of them.
:param list application_type_list: types of the applications,
specified as a comma-separated list. If application_types is not
provided, the API will count the applications of any application
type. In this case, the response shows * to indicate any
application type. Note that we only support at most one
applicationType temporarily. Otherwise, users will expect
an BadRequestException.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/appstatistics'
# TODO: validate state argument
states = ','.join(state_list) if state_list is not None else None
if application_type_list is not None:
application_types = ','.join(application_type_list)
else:
application_types = None
loc_args = (
('states', states),
('applicationTypes', application_types))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def cluster_application_attempts(self, application_id):
"""
With the application attempts API, you can obtain a collection of
resources that represent an application attempt.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts'.format(
appid=application_id)
return self.request(path)
def cluster_application_attempt_info(self, application_id, attempt_id):
"""
With the application attempts API, you can obtain an extended info about
an application attempt.
:param str application_id: The application id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts/{attemptid}'.format(
appid=application_id, attemptid=attempt_id)
return self.request(path)
def cluster_application_attempt_containers(self, application_id, attempt_id):
"""
With the application attempts API, you can obtain an information
about container related to an application attempt.
:param str application_id: The application id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts/{attemptid}/containers'.format(
appid=application_id, attemptid=attempt_id)
return self.request(path)
def cluster_application_state(self, application_id):
"""
With the application state API, you can obtain the current
state of an application.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/state'.format(
appid=application_id)
return self.request(path)
def cluster_application_kill(self, application_id):
"""
With the application kill API, you can kill an application
that is not in FINISHED or FAILED state.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
data = '{"state": "KILLED"}'
path = '/ws/v1/cluster/apps/{appid}/state'.format(
appid=application_id)
return self.update(path, data)
def cluster_nodes(self, state=None, healthy=None):
"""
With the Nodes API, you can obtain a collection of resources, each of
which represents a node.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `healthy`
incorrect
"""
path = '/ws/v1/cluster/nodes'
# TODO: validate state argument
legal_healthy = ['true', 'false']
if healthy is not None and healthy not in legal_healthy:
msg = 'Valid Healthy arguments are true, false'
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('healthy', healthy),
)
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def cluster_node(self, node_id):
"""
A node resource contains information about a node in the cluster.
:param str node_id: The node id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/nodes/{nodeid}'.format(nodeid=node_id)
return self.request(path)
|
toidi/hadoop-yarn-api-python-client | yarn_api_client/resource_manager.py | ResourceManager.cluster_application_attempts | python | def cluster_application_attempts(self, application_id):
path = '/ws/v1/cluster/apps/{appid}/appattempts'.format(
appid=application_id)
return self.request(path) | With the application attempts API, you can obtain a collection of
resources that represent an application attempt.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response` | train | https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/resource_manager.py#L174-L186 | [
"def request(self, api_path, **query_args):\n params = query_args\n api_endpoint = 'http://{}:{}{}'.format(self.address, self.port, api_path)\n\n self.logger.info('API Endpoint {}'.format(api_endpoint))\n\n self._validate_configuration()\n\n response = None\n if self.kerberos_enabled:\n fro... | class ResourceManager(BaseYarnAPI):
"""
The ResourceManager REST API's allow the user to get information about the
cluster - status on the cluster, metrics on the cluster,
scheduler information, information about nodes in the cluster,
and information about applications on the cluster.
If `address` argument is `None` client will try to extract `address` and
`port` from Hadoop configuration files.
:param str address: ResourceManager HTTP address
:param int port: ResourceManager HTTP port
:param int timeout: API connection timeout in seconds
:param boolean kerberos_enabled: Flag identifying is Kerberos Security has been enabled for YARN
"""
def __init__(self, address=None, port=8088, timeout=30, kerberos_enabled=False):
self.address, self.port, self.timeout, self.kerberos_enabled = address, port, timeout, kerberos_enabled
if address is None:
self.logger.debug('Get configuration from hadoop conf dir')
address, port = get_resource_manager_host_port()
self.address, self.port = address, port
def cluster_information(self):
"""
The cluster information resource provides overall information about
the cluster.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/info'
return self.request(path)
def cluster_metrics(self):
"""
The cluster metrics resource provides some overall metrics about the
cluster. More detailed metrics should be retrieved from the jmx
interface.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/metrics'
return self.request(path)
def cluster_scheduler(self):
"""
A scheduler resource contains information about the current scheduler
configured in a cluster. It currently supports both the Fifo and
Capacity Scheduler. You will get different information depending on
which scheduler is configured so be sure to look at the type
information.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/scheduler'
return self.request(path)
def cluster_applications(self, state=None, final_status=None,
user=None, queue=None, limit=None,
started_time_begin=None, started_time_end=None,
finished_time_begin=None, finished_time_end=None):
"""
With the Applications API, you can obtain a collection of resources,
each of which represents an application.
:param str state: state of the application
:param str final_status: the final status of the
application - reported by the application itself
:param str user: user name
:param str queue: queue name
:param str limit: total number of app objects to be returned
:param str started_time_begin: applications with start time beginning
with this time, specified in ms since epoch
:param str started_time_end: applications with start time ending with
this time, specified in ms since epoch
:param str finished_time_begin: applications with finish time
beginning with this time, specified in ms since epoch
:param str finished_time_end: applications with finish time ending
with this time, specified in ms since epoch
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `state` or
`final_status` incorrect
"""
path = '/ws/v1/cluster/apps'
legal_states = set([s for s, _ in YarnApplicationState])
if state is not None and state not in legal_states:
msg = 'Yarn Application State %s is illegal' % (state,)
raise IllegalArgumentError(msg)
legal_final_statuses = set([s for s, _ in FinalApplicationStatus])
if final_status is not None and final_status not in legal_final_statuses:
msg = 'Final Application Status %s is illegal' % (final_status,)
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('finalStatus', final_status),
('user', user),
('queue', queue),
('limit', limit),
('startedTimeBegin', started_time_begin),
('startedTimeEnd', started_time_end),
('finishedTimeBegin', finished_time_begin),
('finishedTimeEnd', finished_time_end))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def cluster_application_statistics(self, state_list=None,
application_type_list=None):
"""
With the Application Statistics API, you can obtain a collection of
triples, each of which contains the application type, the application
state and the number of applications of this type and this state in
ResourceManager context.
This method work in Hadoop > 2.0.0
:param list state_list: states of the applications, specified as a
comma-separated list. If states is not provided, the API will
enumerate all application states and return the counts of them.
:param list application_type_list: types of the applications,
specified as a comma-separated list. If application_types is not
provided, the API will count the applications of any application
type. In this case, the response shows * to indicate any
application type. Note that we only support at most one
applicationType temporarily. Otherwise, users will expect
an BadRequestException.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/appstatistics'
# TODO: validate state argument
states = ','.join(state_list) if state_list is not None else None
if application_type_list is not None:
application_types = ','.join(application_type_list)
else:
application_types = None
loc_args = (
('states', states),
('applicationTypes', application_types))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def cluster_application(self, application_id):
"""
An application resource contains information about a particular
application that was submitted to a cluster.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}'.format(appid=application_id)
return self.request(path)
def cluster_application_attempt_info(self, application_id, attempt_id):
"""
With the application attempts API, you can obtain an extended info about
an application attempt.
:param str application_id: The application id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts/{attemptid}'.format(
appid=application_id, attemptid=attempt_id)
return self.request(path)
def cluster_application_attempt_containers(self, application_id, attempt_id):
"""
With the application attempts API, you can obtain an information
about container related to an application attempt.
:param str application_id: The application id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts/{attemptid}/containers'.format(
appid=application_id, attemptid=attempt_id)
return self.request(path)
def cluster_application_state(self, application_id):
"""
With the application state API, you can obtain the current
state of an application.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/state'.format(
appid=application_id)
return self.request(path)
def cluster_application_kill(self, application_id):
"""
With the application kill API, you can kill an application
that is not in FINISHED or FAILED state.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
data = '{"state": "KILLED"}'
path = '/ws/v1/cluster/apps/{appid}/state'.format(
appid=application_id)
return self.update(path, data)
def cluster_nodes(self, state=None, healthy=None):
"""
With the Nodes API, you can obtain a collection of resources, each of
which represents a node.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `healthy`
incorrect
"""
path = '/ws/v1/cluster/nodes'
# TODO: validate state argument
legal_healthy = ['true', 'false']
if healthy is not None and healthy not in legal_healthy:
msg = 'Valid Healthy arguments are true, false'
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('healthy', healthy),
)
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def cluster_node(self, node_id):
"""
A node resource contains information about a node in the cluster.
:param str node_id: The node id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/nodes/{nodeid}'.format(nodeid=node_id)
return self.request(path)
|
toidi/hadoop-yarn-api-python-client | yarn_api_client/resource_manager.py | ResourceManager.cluster_application_attempt_info | python | def cluster_application_attempt_info(self, application_id, attempt_id):
path = '/ws/v1/cluster/apps/{appid}/appattempts/{attemptid}'.format(
appid=application_id, attemptid=attempt_id)
return self.request(path) | With the application attempts API, you can obtain an extended info about
an application attempt.
:param str application_id: The application id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response` | train | https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/resource_manager.py#L188-L201 | [
"def request(self, api_path, **query_args):\n params = query_args\n api_endpoint = 'http://{}:{}{}'.format(self.address, self.port, api_path)\n\n self.logger.info('API Endpoint {}'.format(api_endpoint))\n\n self._validate_configuration()\n\n response = None\n if self.kerberos_enabled:\n fro... | class ResourceManager(BaseYarnAPI):
"""
The ResourceManager REST API's allow the user to get information about the
cluster - status on the cluster, metrics on the cluster,
scheduler information, information about nodes in the cluster,
and information about applications on the cluster.
If `address` argument is `None` client will try to extract `address` and
`port` from Hadoop configuration files.
:param str address: ResourceManager HTTP address
:param int port: ResourceManager HTTP port
:param int timeout: API connection timeout in seconds
:param boolean kerberos_enabled: Flag identifying is Kerberos Security has been enabled for YARN
"""
def __init__(self, address=None, port=8088, timeout=30, kerberos_enabled=False):
self.address, self.port, self.timeout, self.kerberos_enabled = address, port, timeout, kerberos_enabled
if address is None:
self.logger.debug('Get configuration from hadoop conf dir')
address, port = get_resource_manager_host_port()
self.address, self.port = address, port
def cluster_information(self):
"""
The cluster information resource provides overall information about
the cluster.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/info'
return self.request(path)
def cluster_metrics(self):
"""
The cluster metrics resource provides some overall metrics about the
cluster. More detailed metrics should be retrieved from the jmx
interface.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/metrics'
return self.request(path)
def cluster_scheduler(self):
"""
A scheduler resource contains information about the current scheduler
configured in a cluster. It currently supports both the Fifo and
Capacity Scheduler. You will get different information depending on
which scheduler is configured so be sure to look at the type
information.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/scheduler'
return self.request(path)
def cluster_applications(self, state=None, final_status=None,
user=None, queue=None, limit=None,
started_time_begin=None, started_time_end=None,
finished_time_begin=None, finished_time_end=None):
"""
With the Applications API, you can obtain a collection of resources,
each of which represents an application.
:param str state: state of the application
:param str final_status: the final status of the
application - reported by the application itself
:param str user: user name
:param str queue: queue name
:param str limit: total number of app objects to be returned
:param str started_time_begin: applications with start time beginning
with this time, specified in ms since epoch
:param str started_time_end: applications with start time ending with
this time, specified in ms since epoch
:param str finished_time_begin: applications with finish time
beginning with this time, specified in ms since epoch
:param str finished_time_end: applications with finish time ending
with this time, specified in ms since epoch
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `state` or
`final_status` incorrect
"""
path = '/ws/v1/cluster/apps'
legal_states = set([s for s, _ in YarnApplicationState])
if state is not None and state not in legal_states:
msg = 'Yarn Application State %s is illegal' % (state,)
raise IllegalArgumentError(msg)
legal_final_statuses = set([s for s, _ in FinalApplicationStatus])
if final_status is not None and final_status not in legal_final_statuses:
msg = 'Final Application Status %s is illegal' % (final_status,)
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('finalStatus', final_status),
('user', user),
('queue', queue),
('limit', limit),
('startedTimeBegin', started_time_begin),
('startedTimeEnd', started_time_end),
('finishedTimeBegin', finished_time_begin),
('finishedTimeEnd', finished_time_end))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def cluster_application_statistics(self, state_list=None,
application_type_list=None):
"""
With the Application Statistics API, you can obtain a collection of
triples, each of which contains the application type, the application
state and the number of applications of this type and this state in
ResourceManager context.
This method work in Hadoop > 2.0.0
:param list state_list: states of the applications, specified as a
comma-separated list. If states is not provided, the API will
enumerate all application states and return the counts of them.
:param list application_type_list: types of the applications,
specified as a comma-separated list. If application_types is not
provided, the API will count the applications of any application
type. In this case, the response shows * to indicate any
application type. Note that we only support at most one
applicationType temporarily. Otherwise, users will expect
an BadRequestException.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/appstatistics'
# TODO: validate state argument
states = ','.join(state_list) if state_list is not None else None
if application_type_list is not None:
application_types = ','.join(application_type_list)
else:
application_types = None
loc_args = (
('states', states),
('applicationTypes', application_types))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def cluster_application(self, application_id):
"""
An application resource contains information about a particular
application that was submitted to a cluster.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}'.format(appid=application_id)
return self.request(path)
def cluster_application_attempts(self, application_id):
"""
With the application attempts API, you can obtain a collection of
resources that represent an application attempt.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts'.format(
appid=application_id)
return self.request(path)
def cluster_application_attempt_containers(self, application_id, attempt_id):
"""
With the application attempts API, you can obtain an information
about container related to an application attempt.
:param str application_id: The application id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts/{attemptid}/containers'.format(
appid=application_id, attemptid=attempt_id)
return self.request(path)
def cluster_application_state(self, application_id):
"""
With the application state API, you can obtain the current
state of an application.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/state'.format(
appid=application_id)
return self.request(path)
def cluster_application_kill(self, application_id):
"""
With the application kill API, you can kill an application
that is not in FINISHED or FAILED state.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
data = '{"state": "KILLED"}'
path = '/ws/v1/cluster/apps/{appid}/state'.format(
appid=application_id)
return self.update(path, data)
def cluster_nodes(self, state=None, healthy=None):
"""
With the Nodes API, you can obtain a collection of resources, each of
which represents a node.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `healthy`
incorrect
"""
path = '/ws/v1/cluster/nodes'
# TODO: validate state argument
legal_healthy = ['true', 'false']
if healthy is not None and healthy not in legal_healthy:
msg = 'Valid Healthy arguments are true, false'
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('healthy', healthy),
)
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def cluster_node(self, node_id):
"""
A node resource contains information about a node in the cluster.
:param str node_id: The node id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/nodes/{nodeid}'.format(nodeid=node_id)
return self.request(path)
|
toidi/hadoop-yarn-api-python-client | yarn_api_client/resource_manager.py | ResourceManager.cluster_application_state | python | def cluster_application_state(self, application_id):
path = '/ws/v1/cluster/apps/{appid}/state'.format(
appid=application_id)
return self.request(path) | With the application state API, you can obtain the current
state of an application.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response` | train | https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/resource_manager.py#L218-L230 | [
"def request(self, api_path, **query_args):\n params = query_args\n api_endpoint = 'http://{}:{}{}'.format(self.address, self.port, api_path)\n\n self.logger.info('API Endpoint {}'.format(api_endpoint))\n\n self._validate_configuration()\n\n response = None\n if self.kerberos_enabled:\n fro... | class ResourceManager(BaseYarnAPI):
"""
The ResourceManager REST API's allow the user to get information about the
cluster - status on the cluster, metrics on the cluster,
scheduler information, information about nodes in the cluster,
and information about applications on the cluster.
If `address` argument is `None` client will try to extract `address` and
`port` from Hadoop configuration files.
:param str address: ResourceManager HTTP address
:param int port: ResourceManager HTTP port
:param int timeout: API connection timeout in seconds
:param boolean kerberos_enabled: Flag identifying is Kerberos Security has been enabled for YARN
"""
def __init__(self, address=None, port=8088, timeout=30, kerberos_enabled=False):
self.address, self.port, self.timeout, self.kerberos_enabled = address, port, timeout, kerberos_enabled
if address is None:
self.logger.debug('Get configuration from hadoop conf dir')
address, port = get_resource_manager_host_port()
self.address, self.port = address, port
def cluster_information(self):
"""
The cluster information resource provides overall information about
the cluster.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/info'
return self.request(path)
def cluster_metrics(self):
"""
The cluster metrics resource provides some overall metrics about the
cluster. More detailed metrics should be retrieved from the jmx
interface.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/metrics'
return self.request(path)
def cluster_scheduler(self):
"""
A scheduler resource contains information about the current scheduler
configured in a cluster. It currently supports both the Fifo and
Capacity Scheduler. You will get different information depending on
which scheduler is configured so be sure to look at the type
information.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/scheduler'
return self.request(path)
def cluster_applications(self, state=None, final_status=None,
user=None, queue=None, limit=None,
started_time_begin=None, started_time_end=None,
finished_time_begin=None, finished_time_end=None):
"""
With the Applications API, you can obtain a collection of resources,
each of which represents an application.
:param str state: state of the application
:param str final_status: the final status of the
application - reported by the application itself
:param str user: user name
:param str queue: queue name
:param str limit: total number of app objects to be returned
:param str started_time_begin: applications with start time beginning
with this time, specified in ms since epoch
:param str started_time_end: applications with start time ending with
this time, specified in ms since epoch
:param str finished_time_begin: applications with finish time
beginning with this time, specified in ms since epoch
:param str finished_time_end: applications with finish time ending
with this time, specified in ms since epoch
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `state` or
`final_status` incorrect
"""
path = '/ws/v1/cluster/apps'
legal_states = set([s for s, _ in YarnApplicationState])
if state is not None and state not in legal_states:
msg = 'Yarn Application State %s is illegal' % (state,)
raise IllegalArgumentError(msg)
legal_final_statuses = set([s for s, _ in FinalApplicationStatus])
if final_status is not None and final_status not in legal_final_statuses:
msg = 'Final Application Status %s is illegal' % (final_status,)
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('finalStatus', final_status),
('user', user),
('queue', queue),
('limit', limit),
('startedTimeBegin', started_time_begin),
('startedTimeEnd', started_time_end),
('finishedTimeBegin', finished_time_begin),
('finishedTimeEnd', finished_time_end))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def cluster_application_statistics(self, state_list=None,
application_type_list=None):
"""
With the Application Statistics API, you can obtain a collection of
triples, each of which contains the application type, the application
state and the number of applications of this type and this state in
ResourceManager context.
This method work in Hadoop > 2.0.0
:param list state_list: states of the applications, specified as a
comma-separated list. If states is not provided, the API will
enumerate all application states and return the counts of them.
:param list application_type_list: types of the applications,
specified as a comma-separated list. If application_types is not
provided, the API will count the applications of any application
type. In this case, the response shows * to indicate any
application type. Note that we only support at most one
applicationType temporarily. Otherwise, users will expect
an BadRequestException.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/appstatistics'
# TODO: validate state argument
states = ','.join(state_list) if state_list is not None else None
if application_type_list is not None:
application_types = ','.join(application_type_list)
else:
application_types = None
loc_args = (
('states', states),
('applicationTypes', application_types))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def cluster_application(self, application_id):
"""
An application resource contains information about a particular
application that was submitted to a cluster.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}'.format(appid=application_id)
return self.request(path)
def cluster_application_attempts(self, application_id):
"""
With the application attempts API, you can obtain a collection of
resources that represent an application attempt.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts'.format(
appid=application_id)
return self.request(path)
def cluster_application_attempt_info(self, application_id, attempt_id):
"""
With the application attempts API, you can obtain an extended info about
an application attempt.
:param str application_id: The application id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts/{attemptid}'.format(
appid=application_id, attemptid=attempt_id)
return self.request(path)
def cluster_application_attempt_containers(self, application_id, attempt_id):
"""
With the application attempts API, you can obtain an information
about container related to an application attempt.
:param str application_id: The application id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts/{attemptid}/containers'.format(
appid=application_id, attemptid=attempt_id)
return self.request(path)
def cluster_application_kill(self, application_id):
"""
With the application kill API, you can kill an application
that is not in FINISHED or FAILED state.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
data = '{"state": "KILLED"}'
path = '/ws/v1/cluster/apps/{appid}/state'.format(
appid=application_id)
return self.update(path, data)
def cluster_nodes(self, state=None, healthy=None):
"""
With the Nodes API, you can obtain a collection of resources, each of
which represents a node.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `healthy`
incorrect
"""
path = '/ws/v1/cluster/nodes'
# TODO: validate state argument
legal_healthy = ['true', 'false']
if healthy is not None and healthy not in legal_healthy:
msg = 'Valid Healthy arguments are true, false'
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('healthy', healthy),
)
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def cluster_node(self, node_id):
"""
A node resource contains information about a node in the cluster.
:param str node_id: The node id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/nodes/{nodeid}'.format(nodeid=node_id)
return self.request(path)
|
toidi/hadoop-yarn-api-python-client | yarn_api_client/resource_manager.py | ResourceManager.cluster_application_kill | python | def cluster_application_kill(self, application_id):
data = '{"state": "KILLED"}'
path = '/ws/v1/cluster/apps/{appid}/state'.format(
appid=application_id)
return self.update(path, data) | With the application kill API, you can kill an application
that is not in FINISHED or FAILED state.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response` | train | https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/resource_manager.py#L232-L246 | [
"def update(self, api_path, data):\n api_endpoint = 'http://{}:{}{}'.format(self.address, self.port, api_path)\n\n self.logger.info('API Endpoint {}'.format(api_endpoint))\n\n self._validate_configuration()\n\n response = None\n if self.kerberos_enabled:\n from requests_kerberos import HTTPKer... | class ResourceManager(BaseYarnAPI):
"""
The ResourceManager REST API's allow the user to get information about the
cluster - status on the cluster, metrics on the cluster,
scheduler information, information about nodes in the cluster,
and information about applications on the cluster.
If `address` argument is `None` client will try to extract `address` and
`port` from Hadoop configuration files.
:param str address: ResourceManager HTTP address
:param int port: ResourceManager HTTP port
:param int timeout: API connection timeout in seconds
:param boolean kerberos_enabled: Flag identifying is Kerberos Security has been enabled for YARN
"""
def __init__(self, address=None, port=8088, timeout=30, kerberos_enabled=False):
self.address, self.port, self.timeout, self.kerberos_enabled = address, port, timeout, kerberos_enabled
if address is None:
self.logger.debug('Get configuration from hadoop conf dir')
address, port = get_resource_manager_host_port()
self.address, self.port = address, port
def cluster_information(self):
"""
The cluster information resource provides overall information about
the cluster.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/info'
return self.request(path)
def cluster_metrics(self):
"""
The cluster metrics resource provides some overall metrics about the
cluster. More detailed metrics should be retrieved from the jmx
interface.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/metrics'
return self.request(path)
def cluster_scheduler(self):
"""
A scheduler resource contains information about the current scheduler
configured in a cluster. It currently supports both the Fifo and
Capacity Scheduler. You will get different information depending on
which scheduler is configured so be sure to look at the type
information.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/scheduler'
return self.request(path)
def cluster_applications(self, state=None, final_status=None,
user=None, queue=None, limit=None,
started_time_begin=None, started_time_end=None,
finished_time_begin=None, finished_time_end=None):
"""
With the Applications API, you can obtain a collection of resources,
each of which represents an application.
:param str state: state of the application
:param str final_status: the final status of the
application - reported by the application itself
:param str user: user name
:param str queue: queue name
:param str limit: total number of app objects to be returned
:param str started_time_begin: applications with start time beginning
with this time, specified in ms since epoch
:param str started_time_end: applications with start time ending with
this time, specified in ms since epoch
:param str finished_time_begin: applications with finish time
beginning with this time, specified in ms since epoch
:param str finished_time_end: applications with finish time ending
with this time, specified in ms since epoch
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `state` or
`final_status` incorrect
"""
path = '/ws/v1/cluster/apps'
legal_states = set([s for s, _ in YarnApplicationState])
if state is not None and state not in legal_states:
msg = 'Yarn Application State %s is illegal' % (state,)
raise IllegalArgumentError(msg)
legal_final_statuses = set([s for s, _ in FinalApplicationStatus])
if final_status is not None and final_status not in legal_final_statuses:
msg = 'Final Application Status %s is illegal' % (final_status,)
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('finalStatus', final_status),
('user', user),
('queue', queue),
('limit', limit),
('startedTimeBegin', started_time_begin),
('startedTimeEnd', started_time_end),
('finishedTimeBegin', finished_time_begin),
('finishedTimeEnd', finished_time_end))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def cluster_application_statistics(self, state_list=None,
application_type_list=None):
"""
With the Application Statistics API, you can obtain a collection of
triples, each of which contains the application type, the application
state and the number of applications of this type and this state in
ResourceManager context.
This method work in Hadoop > 2.0.0
:param list state_list: states of the applications, specified as a
comma-separated list. If states is not provided, the API will
enumerate all application states and return the counts of them.
:param list application_type_list: types of the applications,
specified as a comma-separated list. If application_types is not
provided, the API will count the applications of any application
type. In this case, the response shows * to indicate any
application type. Note that we only support at most one
applicationType temporarily. Otherwise, users will expect
an BadRequestException.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/appstatistics'
# TODO: validate state argument
states = ','.join(state_list) if state_list is not None else None
if application_type_list is not None:
application_types = ','.join(application_type_list)
else:
application_types = None
loc_args = (
('states', states),
('applicationTypes', application_types))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def cluster_application(self, application_id):
"""
An application resource contains information about a particular
application that was submitted to a cluster.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}'.format(appid=application_id)
return self.request(path)
def cluster_application_attempts(self, application_id):
"""
With the application attempts API, you can obtain a collection of
resources that represent an application attempt.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts'.format(
appid=application_id)
return self.request(path)
def cluster_application_attempt_info(self, application_id, attempt_id):
"""
With the application attempts API, you can obtain an extended info about
an application attempt.
:param str application_id: The application id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts/{attemptid}'.format(
appid=application_id, attemptid=attempt_id)
return self.request(path)
def cluster_application_attempt_containers(self, application_id, attempt_id):
"""
With the application attempts API, you can obtain an information
about container related to an application attempt.
:param str application_id: The application id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts/{attemptid}/containers'.format(
appid=application_id, attemptid=attempt_id)
return self.request(path)
def cluster_application_state(self, application_id):
"""
With the application state API, you can obtain the current
state of an application.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/state'.format(
appid=application_id)
return self.request(path)
def cluster_nodes(self, state=None, healthy=None):
"""
With the Nodes API, you can obtain a collection of resources, each of
which represents a node.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `healthy`
incorrect
"""
path = '/ws/v1/cluster/nodes'
# TODO: validate state argument
legal_healthy = ['true', 'false']
if healthy is not None and healthy not in legal_healthy:
msg = 'Valid Healthy arguments are true, false'
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('healthy', healthy),
)
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def cluster_node(self, node_id):
"""
A node resource contains information about a node in the cluster.
:param str node_id: The node id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/nodes/{nodeid}'.format(nodeid=node_id)
return self.request(path)
|
toidi/hadoop-yarn-api-python-client | yarn_api_client/resource_manager.py | ResourceManager.cluster_nodes | python | def cluster_nodes(self, state=None, healthy=None):
path = '/ws/v1/cluster/nodes'
# TODO: validate state argument
legal_healthy = ['true', 'false']
if healthy is not None and healthy not in legal_healthy:
msg = 'Valid Healthy arguments are true, false'
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('healthy', healthy),
)
params = self.construct_parameters(loc_args)
return self.request(path, **params) | With the Nodes API, you can obtain a collection of resources, each of
which represents a node.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `healthy`
incorrect | train | https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/resource_manager.py#L248-L272 | [
"def request(self, api_path, **query_args):\n params = query_args\n api_endpoint = 'http://{}:{}{}'.format(self.address, self.port, api_path)\n\n self.logger.info('API Endpoint {}'.format(api_endpoint))\n\n self._validate_configuration()\n\n response = None\n if self.kerberos_enabled:\n fro... | class ResourceManager(BaseYarnAPI):
"""
The ResourceManager REST API's allow the user to get information about the
cluster - status on the cluster, metrics on the cluster,
scheduler information, information about nodes in the cluster,
and information about applications on the cluster.
If `address` argument is `None` client will try to extract `address` and
`port` from Hadoop configuration files.
:param str address: ResourceManager HTTP address
:param int port: ResourceManager HTTP port
:param int timeout: API connection timeout in seconds
:param boolean kerberos_enabled: Flag identifying is Kerberos Security has been enabled for YARN
"""
def __init__(self, address=None, port=8088, timeout=30, kerberos_enabled=False):
self.address, self.port, self.timeout, self.kerberos_enabled = address, port, timeout, kerberos_enabled
if address is None:
self.logger.debug('Get configuration from hadoop conf dir')
address, port = get_resource_manager_host_port()
self.address, self.port = address, port
def cluster_information(self):
"""
The cluster information resource provides overall information about
the cluster.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/info'
return self.request(path)
def cluster_metrics(self):
"""
The cluster metrics resource provides some overall metrics about the
cluster. More detailed metrics should be retrieved from the jmx
interface.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/metrics'
return self.request(path)
def cluster_scheduler(self):
"""
A scheduler resource contains information about the current scheduler
configured in a cluster. It currently supports both the Fifo and
Capacity Scheduler. You will get different information depending on
which scheduler is configured so be sure to look at the type
information.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/scheduler'
return self.request(path)
def cluster_applications(self, state=None, final_status=None,
user=None, queue=None, limit=None,
started_time_begin=None, started_time_end=None,
finished_time_begin=None, finished_time_end=None):
"""
With the Applications API, you can obtain a collection of resources,
each of which represents an application.
:param str state: state of the application
:param str final_status: the final status of the
application - reported by the application itself
:param str user: user name
:param str queue: queue name
:param str limit: total number of app objects to be returned
:param str started_time_begin: applications with start time beginning
with this time, specified in ms since epoch
:param str started_time_end: applications with start time ending with
this time, specified in ms since epoch
:param str finished_time_begin: applications with finish time
beginning with this time, specified in ms since epoch
:param str finished_time_end: applications with finish time ending
with this time, specified in ms since epoch
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `state` or
`final_status` incorrect
"""
path = '/ws/v1/cluster/apps'
legal_states = set([s for s, _ in YarnApplicationState])
if state is not None and state not in legal_states:
msg = 'Yarn Application State %s is illegal' % (state,)
raise IllegalArgumentError(msg)
legal_final_statuses = set([s for s, _ in FinalApplicationStatus])
if final_status is not None and final_status not in legal_final_statuses:
msg = 'Final Application Status %s is illegal' % (final_status,)
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('finalStatus', final_status),
('user', user),
('queue', queue),
('limit', limit),
('startedTimeBegin', started_time_begin),
('startedTimeEnd', started_time_end),
('finishedTimeBegin', finished_time_begin),
('finishedTimeEnd', finished_time_end))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def cluster_application_statistics(self, state_list=None,
application_type_list=None):
"""
With the Application Statistics API, you can obtain a collection of
triples, each of which contains the application type, the application
state and the number of applications of this type and this state in
ResourceManager context.
This method work in Hadoop > 2.0.0
:param list state_list: states of the applications, specified as a
comma-separated list. If states is not provided, the API will
enumerate all application states and return the counts of them.
:param list application_type_list: types of the applications,
specified as a comma-separated list. If application_types is not
provided, the API will count the applications of any application
type. In this case, the response shows * to indicate any
application type. Note that we only support at most one
applicationType temporarily. Otherwise, users will expect
an BadRequestException.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/appstatistics'
# TODO: validate state argument
states = ','.join(state_list) if state_list is not None else None
if application_type_list is not None:
application_types = ','.join(application_type_list)
else:
application_types = None
loc_args = (
('states', states),
('applicationTypes', application_types))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def cluster_application(self, application_id):
"""
An application resource contains information about a particular
application that was submitted to a cluster.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}'.format(appid=application_id)
return self.request(path)
def cluster_application_attempts(self, application_id):
"""
With the application attempts API, you can obtain a collection of
resources that represent an application attempt.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts'.format(
appid=application_id)
return self.request(path)
def cluster_application_attempt_info(self, application_id, attempt_id):
"""
With the application attempts API, you can obtain an extended info about
an application attempt.
:param str application_id: The application id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts/{attemptid}'.format(
appid=application_id, attemptid=attempt_id)
return self.request(path)
def cluster_application_attempt_containers(self, application_id, attempt_id):
"""
With the application attempts API, you can obtain an information
about container related to an application attempt.
:param str application_id: The application id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts/{attemptid}/containers'.format(
appid=application_id, attemptid=attempt_id)
return self.request(path)
def cluster_application_state(self, application_id):
"""
With the application state API, you can obtain the current
state of an application.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/state'.format(
appid=application_id)
return self.request(path)
def cluster_application_kill(self, application_id):
"""
With the application kill API, you can kill an application
that is not in FINISHED or FAILED state.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
data = '{"state": "KILLED"}'
path = '/ws/v1/cluster/apps/{appid}/state'.format(
appid=application_id)
return self.update(path, data)
def cluster_node(self, node_id):
"""
A node resource contains information about a node in the cluster.
:param str node_id: The node id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/nodes/{nodeid}'.format(nodeid=node_id)
return self.request(path)
|
toidi/hadoop-yarn-api-python-client | yarn_api_client/resource_manager.py | ResourceManager.cluster_node | python | def cluster_node(self, node_id):
path = '/ws/v1/cluster/nodes/{nodeid}'.format(nodeid=node_id)
return self.request(path) | A node resource contains information about a node in the cluster.
:param str node_id: The node id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response` | train | https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/resource_manager.py#L274-L284 | [
"def request(self, api_path, **query_args):\n params = query_args\n api_endpoint = 'http://{}:{}{}'.format(self.address, self.port, api_path)\n\n self.logger.info('API Endpoint {}'.format(api_endpoint))\n\n self._validate_configuration()\n\n response = None\n if self.kerberos_enabled:\n fro... | class ResourceManager(BaseYarnAPI):
"""
The ResourceManager REST API's allow the user to get information about the
cluster - status on the cluster, metrics on the cluster,
scheduler information, information about nodes in the cluster,
and information about applications on the cluster.
If `address` argument is `None` client will try to extract `address` and
`port` from Hadoop configuration files.
:param str address: ResourceManager HTTP address
:param int port: ResourceManager HTTP port
:param int timeout: API connection timeout in seconds
:param boolean kerberos_enabled: Flag identifying is Kerberos Security has been enabled for YARN
"""
def __init__(self, address=None, port=8088, timeout=30, kerberos_enabled=False):
self.address, self.port, self.timeout, self.kerberos_enabled = address, port, timeout, kerberos_enabled
if address is None:
self.logger.debug('Get configuration from hadoop conf dir')
address, port = get_resource_manager_host_port()
self.address, self.port = address, port
def cluster_information(self):
"""
The cluster information resource provides overall information about
the cluster.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/info'
return self.request(path)
def cluster_metrics(self):
"""
The cluster metrics resource provides some overall metrics about the
cluster. More detailed metrics should be retrieved from the jmx
interface.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/metrics'
return self.request(path)
def cluster_scheduler(self):
"""
A scheduler resource contains information about the current scheduler
configured in a cluster. It currently supports both the Fifo and
Capacity Scheduler. You will get different information depending on
which scheduler is configured so be sure to look at the type
information.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/scheduler'
return self.request(path)
def cluster_applications(self, state=None, final_status=None,
user=None, queue=None, limit=None,
started_time_begin=None, started_time_end=None,
finished_time_begin=None, finished_time_end=None):
"""
With the Applications API, you can obtain a collection of resources,
each of which represents an application.
:param str state: state of the application
:param str final_status: the final status of the
application - reported by the application itself
:param str user: user name
:param str queue: queue name
:param str limit: total number of app objects to be returned
:param str started_time_begin: applications with start time beginning
with this time, specified in ms since epoch
:param str started_time_end: applications with start time ending with
this time, specified in ms since epoch
:param str finished_time_begin: applications with finish time
beginning with this time, specified in ms since epoch
:param str finished_time_end: applications with finish time ending
with this time, specified in ms since epoch
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `state` or
`final_status` incorrect
"""
path = '/ws/v1/cluster/apps'
legal_states = set([s for s, _ in YarnApplicationState])
if state is not None and state not in legal_states:
msg = 'Yarn Application State %s is illegal' % (state,)
raise IllegalArgumentError(msg)
legal_final_statuses = set([s for s, _ in FinalApplicationStatus])
if final_status is not None and final_status not in legal_final_statuses:
msg = 'Final Application Status %s is illegal' % (final_status,)
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('finalStatus', final_status),
('user', user),
('queue', queue),
('limit', limit),
('startedTimeBegin', started_time_begin),
('startedTimeEnd', started_time_end),
('finishedTimeBegin', finished_time_begin),
('finishedTimeEnd', finished_time_end))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def cluster_application_statistics(self, state_list=None,
application_type_list=None):
"""
With the Application Statistics API, you can obtain a collection of
triples, each of which contains the application type, the application
state and the number of applications of this type and this state in
ResourceManager context.
This method work in Hadoop > 2.0.0
:param list state_list: states of the applications, specified as a
comma-separated list. If states is not provided, the API will
enumerate all application states and return the counts of them.
:param list application_type_list: types of the applications,
specified as a comma-separated list. If application_types is not
provided, the API will count the applications of any application
type. In this case, the response shows * to indicate any
application type. Note that we only support at most one
applicationType temporarily. Otherwise, users will expect
an BadRequestException.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/appstatistics'
# TODO: validate state argument
states = ','.join(state_list) if state_list is not None else None
if application_type_list is not None:
application_types = ','.join(application_type_list)
else:
application_types = None
loc_args = (
('states', states),
('applicationTypes', application_types))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def cluster_application(self, application_id):
"""
An application resource contains information about a particular
application that was submitted to a cluster.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}'.format(appid=application_id)
return self.request(path)
def cluster_application_attempts(self, application_id):
"""
With the application attempts API, you can obtain a collection of
resources that represent an application attempt.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts'.format(
appid=application_id)
return self.request(path)
def cluster_application_attempt_info(self, application_id, attempt_id):
"""
With the application attempts API, you can obtain an extended info about
an application attempt.
:param str application_id: The application id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts/{attemptid}'.format(
appid=application_id, attemptid=attempt_id)
return self.request(path)
def cluster_application_attempt_containers(self, application_id, attempt_id):
"""
With the application attempts API, you can obtain an information
about container related to an application attempt.
:param str application_id: The application id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/appattempts/{attemptid}/containers'.format(
appid=application_id, attemptid=attempt_id)
return self.request(path)
def cluster_application_state(self, application_id):
"""
With the application state API, you can obtain the current
state of an application.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/apps/{appid}/state'.format(
appid=application_id)
return self.request(path)
def cluster_application_kill(self, application_id):
"""
With the application kill API, you can kill an application
that is not in FINISHED or FAILED state.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
data = '{"state": "KILLED"}'
path = '/ws/v1/cluster/apps/{appid}/state'.format(
appid=application_id)
return self.update(path, data)
def cluster_nodes(self, state=None, healthy=None):
"""
With the Nodes API, you can obtain a collection of resources, each of
which represents a node.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `healthy`
incorrect
"""
path = '/ws/v1/cluster/nodes'
# TODO: validate state argument
legal_healthy = ['true', 'false']
if healthy is not None and healthy not in legal_healthy:
msg = 'Valid Healthy arguments are true, false'
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('healthy', healthy),
)
params = self.construct_parameters(loc_args)
return self.request(path, **params)
|
toidi/hadoop-yarn-api-python-client | yarn_api_client/application_master.py | ApplicationMaster.application_information | python | def application_information(self, application_id):
path = '/proxy/{appid}/ws/v1/mapreduce/info'.format(
appid=application_id)
return self.request(path) | The MapReduce application master information resource provides overall
information about that mapreduce application master.
This includes application id, time it was started, user, name, etc.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response` | train | https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/application_master.py#L30-L42 | [
"def request(self, api_path, **query_args):\n params = query_args\n api_endpoint = 'http://{}:{}{}'.format(self.address, self.port, api_path)\n\n self.logger.info('API Endpoint {}'.format(api_endpoint))\n\n self._validate_configuration()\n\n response = None\n if self.kerberos_enabled:\n fro... | class ApplicationMaster(BaseYarnAPI):
"""
The MapReduce Application Master REST API's allow the user to get status
on the running MapReduce application master. Currently this is the
equivalent to a running MapReduce job. The information includes the jobs
the app master is running and all the job particulars like tasks,
counters, configuration, attempts, etc.
If `address` argument is `None` client will try to extract `address` and
`port` from Hadoop configuration files.
:param str address: Proxy HTTP address
:param int port: Proxy HTTP port
:param int timeout: API connection timeout in seconds
:param boolean kerberos_enabled: Flag identifying is Kerberos Security has been enabled for YARN
"""
def __init__(self, address=None, port=8088, timeout=30, kerberos_enabled=False):
self.address, self.port, self.timeout, self.kerberos_enabled = address, port, timeout, kerberos_enabled
if address is None:
self.logger.debug('Get configuration from hadoop conf dir')
address, port = get_webproxy_host_port()
self.address, self.port = address, port
def jobs(self, application_id):
"""
The jobs resource provides a list of the jobs running on this
application master.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs'.format(
appid=application_id)
return self.request(path)
def job(self, application_id, job_id):
"""
A job resource contains information about a particular job that was
started by this application master. Certain fields are only accessible
if user has permissions - depends on acl settings.
:param str application_id: The application id
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}'.format(
appid=application_id, jobid=job_id)
return self.request(path)
def job_attempts(self, job_id):
"""
With the job attempts API, you can obtain a collection of resources
that represent the job attempts.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
pass
def job_counters(self, application_id, job_id):
"""
With the job counters API, you can object a collection of resources
that represent all the counters for that job.
:param str application_id: The application id
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/counters'.format(
appid=application_id, jobid=job_id)
return self.request(path)
def job_conf(self, application_id, job_id):
"""
A job configuration resource contains information about the job
configuration for this job.
:param str application_id: The application id
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/conf'.format(
appid=application_id, jobid=job_id)
return self.request(path)
def job_tasks(self, application_id, job_id):
"""
With the tasks API, you can obtain a collection of resources that
represent all the tasks for a job.
:param str application_id: The application id
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks'.format(
appid=application_id, jobid=job_id)
return self.request(path)
def job_task(self, application_id, job_id, task_id):
"""
A Task resource contains information about a particular
task within a job.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}'.format(
appid=application_id, jobid=job_id, taskid=task_id)
return self.request(path)
def task_counters(self, application_id, job_id, task_id):
"""
With the task counters API, you can object a collection of resources
that represent all the counters for that task.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}/counters'.format(
appid=application_id, jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempts(self, application_id, job_id, task_id):
"""
With the task attempts API, you can obtain a collection of resources
that represent a task attempt within a job.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts'.format(
appid=application_id, jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempt(self, application_id, job_id, task_id, attempt_id):
"""
A Task Attempt resource contains information about a particular task
attempt within a job.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}/attempt/{attemptid}'.format(
appid=application_id, jobid=job_id, taskid=task_id,
attemptid=attempt_id)
return self.request(path)
def task_attempt_counters(self, application_id, job_id, task_id, attempt_id):
"""
With the task attempt counters API, you can object a collection
of resources that represent al the counters for that task attempt.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}/attempt/{attemptid}/counters'.format(
appid=application_id, jobid=job_id, taskid=task_id,
attemptid=attempt_id)
return self.request(path)
|
toidi/hadoop-yarn-api-python-client | yarn_api_client/application_master.py | ApplicationMaster.jobs | python | def jobs(self, application_id):
path = '/proxy/{appid}/ws/v1/mapreduce/jobs'.format(
appid=application_id)
return self.request(path) | The jobs resource provides a list of the jobs running on this
application master.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response` | train | https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/application_master.py#L44-L56 | [
"def request(self, api_path, **query_args):\n params = query_args\n api_endpoint = 'http://{}:{}{}'.format(self.address, self.port, api_path)\n\n self.logger.info('API Endpoint {}'.format(api_endpoint))\n\n self._validate_configuration()\n\n response = None\n if self.kerberos_enabled:\n fro... | class ApplicationMaster(BaseYarnAPI):
"""
The MapReduce Application Master REST API's allow the user to get status
on the running MapReduce application master. Currently this is the
equivalent to a running MapReduce job. The information includes the jobs
the app master is running and all the job particulars like tasks,
counters, configuration, attempts, etc.
If `address` argument is `None` client will try to extract `address` and
`port` from Hadoop configuration files.
:param str address: Proxy HTTP address
:param int port: Proxy HTTP port
:param int timeout: API connection timeout in seconds
:param boolean kerberos_enabled: Flag identifying is Kerberos Security has been enabled for YARN
"""
def __init__(self, address=None, port=8088, timeout=30, kerberos_enabled=False):
self.address, self.port, self.timeout, self.kerberos_enabled = address, port, timeout, kerberos_enabled
if address is None:
self.logger.debug('Get configuration from hadoop conf dir')
address, port = get_webproxy_host_port()
self.address, self.port = address, port
def application_information(self, application_id):
"""
The MapReduce application master information resource provides overall
information about that mapreduce application master.
This includes application id, time it was started, user, name, etc.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/info'.format(
appid=application_id)
return self.request(path)
def job(self, application_id, job_id):
"""
A job resource contains information about a particular job that was
started by this application master. Certain fields are only accessible
if user has permissions - depends on acl settings.
:param str application_id: The application id
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}'.format(
appid=application_id, jobid=job_id)
return self.request(path)
def job_attempts(self, job_id):
"""
With the job attempts API, you can obtain a collection of resources
that represent the job attempts.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
pass
def job_counters(self, application_id, job_id):
"""
With the job counters API, you can object a collection of resources
that represent all the counters for that job.
:param str application_id: The application id
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/counters'.format(
appid=application_id, jobid=job_id)
return self.request(path)
def job_conf(self, application_id, job_id):
"""
A job configuration resource contains information about the job
configuration for this job.
:param str application_id: The application id
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/conf'.format(
appid=application_id, jobid=job_id)
return self.request(path)
def job_tasks(self, application_id, job_id):
"""
With the tasks API, you can obtain a collection of resources that
represent all the tasks for a job.
:param str application_id: The application id
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks'.format(
appid=application_id, jobid=job_id)
return self.request(path)
def job_task(self, application_id, job_id, task_id):
"""
A Task resource contains information about a particular
task within a job.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}'.format(
appid=application_id, jobid=job_id, taskid=task_id)
return self.request(path)
def task_counters(self, application_id, job_id, task_id):
"""
With the task counters API, you can object a collection of resources
that represent all the counters for that task.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}/counters'.format(
appid=application_id, jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempts(self, application_id, job_id, task_id):
"""
With the task attempts API, you can obtain a collection of resources
that represent a task attempt within a job.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts'.format(
appid=application_id, jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempt(self, application_id, job_id, task_id, attempt_id):
"""
A Task Attempt resource contains information about a particular task
attempt within a job.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}/attempt/{attemptid}'.format(
appid=application_id, jobid=job_id, taskid=task_id,
attemptid=attempt_id)
return self.request(path)
def task_attempt_counters(self, application_id, job_id, task_id, attempt_id):
"""
With the task attempt counters API, you can object a collection
of resources that represent al the counters for that task attempt.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}/attempt/{attemptid}/counters'.format(
appid=application_id, jobid=job_id, taskid=task_id,
attemptid=attempt_id)
return self.request(path)
|
toidi/hadoop-yarn-api-python-client | yarn_api_client/application_master.py | ApplicationMaster.job | python | def job(self, application_id, job_id):
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}'.format(
appid=application_id, jobid=job_id)
return self.request(path) | A job resource contains information about a particular job that was
started by this application master. Certain fields are only accessible
if user has permissions - depends on acl settings.
:param str application_id: The application id
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response` | train | https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/application_master.py#L58-L72 | [
"def request(self, api_path, **query_args):\n params = query_args\n api_endpoint = 'http://{}:{}{}'.format(self.address, self.port, api_path)\n\n self.logger.info('API Endpoint {}'.format(api_endpoint))\n\n self._validate_configuration()\n\n response = None\n if self.kerberos_enabled:\n fro... | class ApplicationMaster(BaseYarnAPI):
"""
The MapReduce Application Master REST API's allow the user to get status
on the running MapReduce application master. Currently this is the
equivalent to a running MapReduce job. The information includes the jobs
the app master is running and all the job particulars like tasks,
counters, configuration, attempts, etc.
If `address` argument is `None` client will try to extract `address` and
`port` from Hadoop configuration files.
:param str address: Proxy HTTP address
:param int port: Proxy HTTP port
:param int timeout: API connection timeout in seconds
:param boolean kerberos_enabled: Flag identifying is Kerberos Security has been enabled for YARN
"""
def __init__(self, address=None, port=8088, timeout=30, kerberos_enabled=False):
self.address, self.port, self.timeout, self.kerberos_enabled = address, port, timeout, kerberos_enabled
if address is None:
self.logger.debug('Get configuration from hadoop conf dir')
address, port = get_webproxy_host_port()
self.address, self.port = address, port
def application_information(self, application_id):
"""
The MapReduce application master information resource provides overall
information about that mapreduce application master.
This includes application id, time it was started, user, name, etc.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/info'.format(
appid=application_id)
return self.request(path)
def jobs(self, application_id):
"""
The jobs resource provides a list of the jobs running on this
application master.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs'.format(
appid=application_id)
return self.request(path)
def job_attempts(self, job_id):
"""
With the job attempts API, you can obtain a collection of resources
that represent the job attempts.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
pass
def job_counters(self, application_id, job_id):
"""
With the job counters API, you can object a collection of resources
that represent all the counters for that job.
:param str application_id: The application id
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/counters'.format(
appid=application_id, jobid=job_id)
return self.request(path)
def job_conf(self, application_id, job_id):
"""
A job configuration resource contains information about the job
configuration for this job.
:param str application_id: The application id
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/conf'.format(
appid=application_id, jobid=job_id)
return self.request(path)
def job_tasks(self, application_id, job_id):
"""
With the tasks API, you can obtain a collection of resources that
represent all the tasks for a job.
:param str application_id: The application id
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks'.format(
appid=application_id, jobid=job_id)
return self.request(path)
def job_task(self, application_id, job_id, task_id):
"""
A Task resource contains information about a particular
task within a job.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}'.format(
appid=application_id, jobid=job_id, taskid=task_id)
return self.request(path)
def task_counters(self, application_id, job_id, task_id):
"""
With the task counters API, you can object a collection of resources
that represent all the counters for that task.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}/counters'.format(
appid=application_id, jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempts(self, application_id, job_id, task_id):
"""
With the task attempts API, you can obtain a collection of resources
that represent a task attempt within a job.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts'.format(
appid=application_id, jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempt(self, application_id, job_id, task_id, attempt_id):
"""
A Task Attempt resource contains information about a particular task
attempt within a job.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}/attempt/{attemptid}'.format(
appid=application_id, jobid=job_id, taskid=task_id,
attemptid=attempt_id)
return self.request(path)
def task_attempt_counters(self, application_id, job_id, task_id, attempt_id):
"""
With the task attempt counters API, you can object a collection
of resources that represent al the counters for that task attempt.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}/attempt/{attemptid}/counters'.format(
appid=application_id, jobid=job_id, taskid=task_id,
attemptid=attempt_id)
return self.request(path)
|
toidi/hadoop-yarn-api-python-client | yarn_api_client/application_master.py | ApplicationMaster.job_task | python | def job_task(self, application_id, job_id, task_id):
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}'.format(
appid=application_id, jobid=job_id, taskid=task_id)
return self.request(path) | A Task resource contains information about a particular
task within a job.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response` | train | https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/application_master.py#L130-L144 | [
"def request(self, api_path, **query_args):\n params = query_args\n api_endpoint = 'http://{}:{}{}'.format(self.address, self.port, api_path)\n\n self.logger.info('API Endpoint {}'.format(api_endpoint))\n\n self._validate_configuration()\n\n response = None\n if self.kerberos_enabled:\n fro... | class ApplicationMaster(BaseYarnAPI):
"""
The MapReduce Application Master REST API's allow the user to get status
on the running MapReduce application master. Currently this is the
equivalent to a running MapReduce job. The information includes the jobs
the app master is running and all the job particulars like tasks,
counters, configuration, attempts, etc.
If `address` argument is `None` client will try to extract `address` and
`port` from Hadoop configuration files.
:param str address: Proxy HTTP address
:param int port: Proxy HTTP port
:param int timeout: API connection timeout in seconds
:param boolean kerberos_enabled: Flag identifying is Kerberos Security has been enabled for YARN
"""
def __init__(self, address=None, port=8088, timeout=30, kerberos_enabled=False):
self.address, self.port, self.timeout, self.kerberos_enabled = address, port, timeout, kerberos_enabled
if address is None:
self.logger.debug('Get configuration from hadoop conf dir')
address, port = get_webproxy_host_port()
self.address, self.port = address, port
def application_information(self, application_id):
"""
The MapReduce application master information resource provides overall
information about that mapreduce application master.
This includes application id, time it was started, user, name, etc.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/info'.format(
appid=application_id)
return self.request(path)
def jobs(self, application_id):
"""
The jobs resource provides a list of the jobs running on this
application master.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs'.format(
appid=application_id)
return self.request(path)
def job(self, application_id, job_id):
"""
A job resource contains information about a particular job that was
started by this application master. Certain fields are only accessible
if user has permissions - depends on acl settings.
:param str application_id: The application id
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}'.format(
appid=application_id, jobid=job_id)
return self.request(path)
def job_attempts(self, job_id):
"""
With the job attempts API, you can obtain a collection of resources
that represent the job attempts.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
pass
def job_counters(self, application_id, job_id):
"""
With the job counters API, you can object a collection of resources
that represent all the counters for that job.
:param str application_id: The application id
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/counters'.format(
appid=application_id, jobid=job_id)
return self.request(path)
def job_conf(self, application_id, job_id):
"""
A job configuration resource contains information about the job
configuration for this job.
:param str application_id: The application id
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/conf'.format(
appid=application_id, jobid=job_id)
return self.request(path)
def job_tasks(self, application_id, job_id):
"""
With the tasks API, you can obtain a collection of resources that
represent all the tasks for a job.
:param str application_id: The application id
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks'.format(
appid=application_id, jobid=job_id)
return self.request(path)
def task_counters(self, application_id, job_id, task_id):
"""
With the task counters API, you can object a collection of resources
that represent all the counters for that task.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}/counters'.format(
appid=application_id, jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempts(self, application_id, job_id, task_id):
"""
With the task attempts API, you can obtain a collection of resources
that represent a task attempt within a job.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts'.format(
appid=application_id, jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempt(self, application_id, job_id, task_id, attempt_id):
"""
A Task Attempt resource contains information about a particular task
attempt within a job.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}/attempt/{attemptid}'.format(
appid=application_id, jobid=job_id, taskid=task_id,
attemptid=attempt_id)
return self.request(path)
def task_attempt_counters(self, application_id, job_id, task_id, attempt_id):
"""
With the task attempt counters API, you can object a collection
of resources that represent al the counters for that task attempt.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}/attempt/{attemptid}/counters'.format(
appid=application_id, jobid=job_id, taskid=task_id,
attemptid=attempt_id)
return self.request(path)
|
toidi/hadoop-yarn-api-python-client | yarn_api_client/history_server.py | HistoryServer.jobs | python | def jobs(self, state=None, user=None, queue=None, limit=None,
started_time_begin=None, started_time_end=None,
finished_time_begin=None, finished_time_end=None):
path = '/ws/v1/history/mapreduce/jobs'
legal_states = set([s for s, _ in JobStateInternal])
if state is not None and state not in legal_states:
msg = 'Job Internal State %s is illegal' % (state,)
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('user', user),
('queue', queue),
('limit', limit),
('startedTimeBegin', started_time_begin),
('startedTimeEnd', started_time_end),
('finishedTimeBegin', finished_time_begin),
('finishedTimeEnd', finished_time_end))
params = self.construct_parameters(loc_args)
return self.request(path, **params) | The jobs resource provides a list of the MapReduce jobs that have
finished. It does not currently return a full list of parameters.
:param str user: user name
:param str state: the job state
:param str queue: queue name
:param str limit: total number of app objects to be returned
:param str started_time_begin: jobs with start time beginning with
this time, specified in ms since epoch
:param str started_time_end: jobs with start time ending with this
time, specified in ms since epoch
:param str finished_time_begin: jobs with finish time beginning with
this time, specified in ms since epoch
:param str finished_time_end: jobs with finish time ending with this
time, specified in ms since epoch
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `state`
incorrect | train | https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/history_server.py#L42-L85 | [
"def request(self, api_path, **query_args):\n params = query_args\n api_endpoint = 'http://{}:{}{}'.format(self.address, self.port, api_path)\n\n self.logger.info('API Endpoint {}'.format(api_endpoint))\n\n self._validate_configuration()\n\n response = None\n if self.kerberos_enabled:\n fro... | class HistoryServer(BaseYarnAPI):
"""
The history server REST API's allow the user to get status on finished
applications. Currently it only supports MapReduce and provides
information on finished jobs.
If `address` argument is `None` client will try to extract `address` and
`port` from Hadoop configuration files.
:param str address: HistoryServer HTTP address
:param int port: HistoryServer HTTP port
:param int timeout: API connection timeout in seconds
:param boolean kerberos_enabled: Flag identifying is Kerberos Security has been enabled for YARN
"""
def __init__(self, address=None, port=19888, timeout=30, kerberos_enabled=False):
self.address, self.port, self.timeout, self.kerberos_enabled = address, port, timeout, kerberos_enabled
if address is None:
self.logger.debug('Get information from hadoop conf dir')
address, port = get_jobhistory_host_port()
self.address, self.port = address, port
def application_information(self):
"""
The history server information resource provides overall information
about the history server.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/info'
return self.request(path)
def job(self, job_id):
"""
A Job resource contains information about a particular job identified
by jobid.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}'.format(jobid=job_id)
return self.request(path)
def job_attempts(self, job_id):
"""
With the job attempts API, you can obtain a collection of resources
that represent a job attempt.
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/jobattempts'.format(
jobid=job_id)
return self.request(path)
def job_counters(self, job_id):
"""
With the job counters API, you can object a collection of resources
that represent al the counters for that job.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/counters'.format(
jobid=job_id)
return self.request(path)
def job_conf(self, job_id):
"""
A job configuration resource contains information about the job
configuration for this job.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/conf'.format(jobid=job_id)
return self.request(path)
def job_tasks(self, job_id, type=None):
"""
With the tasks API, you can obtain a collection of resources that
represent a task within a job.
:param str job_id: The job id
:param str type: type of task, valid values are m or r. m for map
task or r for reduce task
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks'.format(
jobid=job_id)
# m - for map
# r - for reduce
valid_types = ['m', 'r']
if type is not None and type not in valid_types:
msg = 'Job type %s is illegal' % (type,)
raise IllegalArgumentError(msg)
params = {}
if type is not None:
params['type'] = type
return self.request(path, **params)
def job_task(self, job_id, task_id):
"""
A Task resource contains information about a particular task
within a job.
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}'.format(
jobid=job_id, taskid=task_id)
return self.request(path)
def task_counters(self, job_id, task_id):
"""
With the task counters API, you can object a collection of resources
that represent all the counters for that task.
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/counters'.format(
jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempts(self, job_id, task_id):
"""
With the task attempts API, you can obtain a collection of resources
that represent a task attempt within a job.
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts'.format(
jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempt(self, job_id, task_id, attempt_id):
"""
A Task Attempt resource contains information about a particular task
attempt within a job.
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts/{attemptid}'.format(
jobid=job_id, taskid=task_id, attemptid=attempt_id)
return self.request(path)
def task_attempt_counters(self, job_id, task_id, attempt_id):
"""
With the task attempt counters API, you can object a collection of
resources that represent al the counters for that task attempt.
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts/{attemptid}/counters'.format(
jobid=job_id, taskid=task_id, attemptid=attempt_id)
return self.request(path)
|
toidi/hadoop-yarn-api-python-client | yarn_api_client/history_server.py | HistoryServer.job | python | def job(self, job_id):
path = '/ws/v1/history/mapreduce/jobs/{jobid}'.format(jobid=job_id)
return self.request(path) | A Job resource contains information about a particular job identified
by jobid.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response` | train | https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/history_server.py#L87-L98 | [
"def request(self, api_path, **query_args):\n params = query_args\n api_endpoint = 'http://{}:{}{}'.format(self.address, self.port, api_path)\n\n self.logger.info('API Endpoint {}'.format(api_endpoint))\n\n self._validate_configuration()\n\n response = None\n if self.kerberos_enabled:\n fro... | class HistoryServer(BaseYarnAPI):
"""
The history server REST API's allow the user to get status on finished
applications. Currently it only supports MapReduce and provides
information on finished jobs.
If `address` argument is `None` client will try to extract `address` and
`port` from Hadoop configuration files.
:param str address: HistoryServer HTTP address
:param int port: HistoryServer HTTP port
:param int timeout: API connection timeout in seconds
:param boolean kerberos_enabled: Flag identifying is Kerberos Security has been enabled for YARN
"""
def __init__(self, address=None, port=19888, timeout=30, kerberos_enabled=False):
self.address, self.port, self.timeout, self.kerberos_enabled = address, port, timeout, kerberos_enabled
if address is None:
self.logger.debug('Get information from hadoop conf dir')
address, port = get_jobhistory_host_port()
self.address, self.port = address, port
def application_information(self):
"""
The history server information resource provides overall information
about the history server.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/info'
return self.request(path)
def jobs(self, state=None, user=None, queue=None, limit=None,
started_time_begin=None, started_time_end=None,
finished_time_begin=None, finished_time_end=None):
"""
The jobs resource provides a list of the MapReduce jobs that have
finished. It does not currently return a full list of parameters.
:param str user: user name
:param str state: the job state
:param str queue: queue name
:param str limit: total number of app objects to be returned
:param str started_time_begin: jobs with start time beginning with
this time, specified in ms since epoch
:param str started_time_end: jobs with start time ending with this
time, specified in ms since epoch
:param str finished_time_begin: jobs with finish time beginning with
this time, specified in ms since epoch
:param str finished_time_end: jobs with finish time ending with this
time, specified in ms since epoch
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `state`
incorrect
"""
path = '/ws/v1/history/mapreduce/jobs'
legal_states = set([s for s, _ in JobStateInternal])
if state is not None and state not in legal_states:
msg = 'Job Internal State %s is illegal' % (state,)
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('user', user),
('queue', queue),
('limit', limit),
('startedTimeBegin', started_time_begin),
('startedTimeEnd', started_time_end),
('finishedTimeBegin', finished_time_begin),
('finishedTimeEnd', finished_time_end))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def job_attempts(self, job_id):
"""
With the job attempts API, you can obtain a collection of resources
that represent a job attempt.
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/jobattempts'.format(
jobid=job_id)
return self.request(path)
def job_counters(self, job_id):
"""
With the job counters API, you can object a collection of resources
that represent al the counters for that job.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/counters'.format(
jobid=job_id)
return self.request(path)
def job_conf(self, job_id):
"""
A job configuration resource contains information about the job
configuration for this job.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/conf'.format(jobid=job_id)
return self.request(path)
def job_tasks(self, job_id, type=None):
"""
With the tasks API, you can obtain a collection of resources that
represent a task within a job.
:param str job_id: The job id
:param str type: type of task, valid values are m or r. m for map
task or r for reduce task
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks'.format(
jobid=job_id)
# m - for map
# r - for reduce
valid_types = ['m', 'r']
if type is not None and type not in valid_types:
msg = 'Job type %s is illegal' % (type,)
raise IllegalArgumentError(msg)
params = {}
if type is not None:
params['type'] = type
return self.request(path, **params)
def job_task(self, job_id, task_id):
"""
A Task resource contains information about a particular task
within a job.
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}'.format(
jobid=job_id, taskid=task_id)
return self.request(path)
def task_counters(self, job_id, task_id):
"""
With the task counters API, you can object a collection of resources
that represent all the counters for that task.
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/counters'.format(
jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempts(self, job_id, task_id):
"""
With the task attempts API, you can obtain a collection of resources
that represent a task attempt within a job.
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts'.format(
jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempt(self, job_id, task_id, attempt_id):
"""
A Task Attempt resource contains information about a particular task
attempt within a job.
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts/{attemptid}'.format(
jobid=job_id, taskid=task_id, attemptid=attempt_id)
return self.request(path)
def task_attempt_counters(self, job_id, task_id, attempt_id):
"""
With the task attempt counters API, you can object a collection of
resources that represent al the counters for that task attempt.
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts/{attemptid}/counters'.format(
jobid=job_id, taskid=task_id, attemptid=attempt_id)
return self.request(path)
|
toidi/hadoop-yarn-api-python-client | yarn_api_client/history_server.py | HistoryServer.job_attempts | python | def job_attempts(self, job_id):
path = '/ws/v1/history/mapreduce/jobs/{jobid}/jobattempts'.format(
jobid=job_id)
return self.request(path) | With the job attempts API, you can obtain a collection of resources
that represent a job attempt. | train | https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/history_server.py#L100-L108 | [
"def request(self, api_path, **query_args):\n params = query_args\n api_endpoint = 'http://{}:{}{}'.format(self.address, self.port, api_path)\n\n self.logger.info('API Endpoint {}'.format(api_endpoint))\n\n self._validate_configuration()\n\n response = None\n if self.kerberos_enabled:\n fro... | class HistoryServer(BaseYarnAPI):
"""
The history server REST API's allow the user to get status on finished
applications. Currently it only supports MapReduce and provides
information on finished jobs.
If `address` argument is `None` client will try to extract `address` and
`port` from Hadoop configuration files.
:param str address: HistoryServer HTTP address
:param int port: HistoryServer HTTP port
:param int timeout: API connection timeout in seconds
:param boolean kerberos_enabled: Flag identifying is Kerberos Security has been enabled for YARN
"""
def __init__(self, address=None, port=19888, timeout=30, kerberos_enabled=False):
self.address, self.port, self.timeout, self.kerberos_enabled = address, port, timeout, kerberos_enabled
if address is None:
self.logger.debug('Get information from hadoop conf dir')
address, port = get_jobhistory_host_port()
self.address, self.port = address, port
def application_information(self):
"""
The history server information resource provides overall information
about the history server.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/info'
return self.request(path)
def jobs(self, state=None, user=None, queue=None, limit=None,
started_time_begin=None, started_time_end=None,
finished_time_begin=None, finished_time_end=None):
"""
The jobs resource provides a list of the MapReduce jobs that have
finished. It does not currently return a full list of parameters.
:param str user: user name
:param str state: the job state
:param str queue: queue name
:param str limit: total number of app objects to be returned
:param str started_time_begin: jobs with start time beginning with
this time, specified in ms since epoch
:param str started_time_end: jobs with start time ending with this
time, specified in ms since epoch
:param str finished_time_begin: jobs with finish time beginning with
this time, specified in ms since epoch
:param str finished_time_end: jobs with finish time ending with this
time, specified in ms since epoch
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `state`
incorrect
"""
path = '/ws/v1/history/mapreduce/jobs'
legal_states = set([s for s, _ in JobStateInternal])
if state is not None and state not in legal_states:
msg = 'Job Internal State %s is illegal' % (state,)
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('user', user),
('queue', queue),
('limit', limit),
('startedTimeBegin', started_time_begin),
('startedTimeEnd', started_time_end),
('finishedTimeBegin', finished_time_begin),
('finishedTimeEnd', finished_time_end))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def job(self, job_id):
"""
A Job resource contains information about a particular job identified
by jobid.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}'.format(jobid=job_id)
return self.request(path)
def job_counters(self, job_id):
"""
With the job counters API, you can object a collection of resources
that represent al the counters for that job.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/counters'.format(
jobid=job_id)
return self.request(path)
def job_conf(self, job_id):
"""
A job configuration resource contains information about the job
configuration for this job.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/conf'.format(jobid=job_id)
return self.request(path)
def job_tasks(self, job_id, type=None):
"""
With the tasks API, you can obtain a collection of resources that
represent a task within a job.
:param str job_id: The job id
:param str type: type of task, valid values are m or r. m for map
task or r for reduce task
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks'.format(
jobid=job_id)
# m - for map
# r - for reduce
valid_types = ['m', 'r']
if type is not None and type not in valid_types:
msg = 'Job type %s is illegal' % (type,)
raise IllegalArgumentError(msg)
params = {}
if type is not None:
params['type'] = type
return self.request(path, **params)
def job_task(self, job_id, task_id):
"""
A Task resource contains information about a particular task
within a job.
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}'.format(
jobid=job_id, taskid=task_id)
return self.request(path)
def task_counters(self, job_id, task_id):
"""
With the task counters API, you can object a collection of resources
that represent all the counters for that task.
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/counters'.format(
jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempts(self, job_id, task_id):
"""
With the task attempts API, you can obtain a collection of resources
that represent a task attempt within a job.
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts'.format(
jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempt(self, job_id, task_id, attempt_id):
"""
A Task Attempt resource contains information about a particular task
attempt within a job.
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts/{attemptid}'.format(
jobid=job_id, taskid=task_id, attemptid=attempt_id)
return self.request(path)
def task_attempt_counters(self, job_id, task_id, attempt_id):
"""
With the task attempt counters API, you can object a collection of
resources that represent al the counters for that task attempt.
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts/{attemptid}/counters'.format(
jobid=job_id, taskid=task_id, attemptid=attempt_id)
return self.request(path)
|
toidi/hadoop-yarn-api-python-client | yarn_api_client/history_server.py | HistoryServer.job_counters | python | def job_counters(self, job_id):
path = '/ws/v1/history/mapreduce/jobs/{jobid}/counters'.format(
jobid=job_id)
return self.request(path) | With the job counters API, you can object a collection of resources
that represent al the counters for that job.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response` | train | https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/history_server.py#L110-L122 | [
"def request(self, api_path, **query_args):\n params = query_args\n api_endpoint = 'http://{}:{}{}'.format(self.address, self.port, api_path)\n\n self.logger.info('API Endpoint {}'.format(api_endpoint))\n\n self._validate_configuration()\n\n response = None\n if self.kerberos_enabled:\n fro... | class HistoryServer(BaseYarnAPI):
"""
The history server REST API's allow the user to get status on finished
applications. Currently it only supports MapReduce and provides
information on finished jobs.
If `address` argument is `None` client will try to extract `address` and
`port` from Hadoop configuration files.
:param str address: HistoryServer HTTP address
:param int port: HistoryServer HTTP port
:param int timeout: API connection timeout in seconds
:param boolean kerberos_enabled: Flag identifying is Kerberos Security has been enabled for YARN
"""
def __init__(self, address=None, port=19888, timeout=30, kerberos_enabled=False):
self.address, self.port, self.timeout, self.kerberos_enabled = address, port, timeout, kerberos_enabled
if address is None:
self.logger.debug('Get information from hadoop conf dir')
address, port = get_jobhistory_host_port()
self.address, self.port = address, port
def application_information(self):
"""
The history server information resource provides overall information
about the history server.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/info'
return self.request(path)
def jobs(self, state=None, user=None, queue=None, limit=None,
started_time_begin=None, started_time_end=None,
finished_time_begin=None, finished_time_end=None):
"""
The jobs resource provides a list of the MapReduce jobs that have
finished. It does not currently return a full list of parameters.
:param str user: user name
:param str state: the job state
:param str queue: queue name
:param str limit: total number of app objects to be returned
:param str started_time_begin: jobs with start time beginning with
this time, specified in ms since epoch
:param str started_time_end: jobs with start time ending with this
time, specified in ms since epoch
:param str finished_time_begin: jobs with finish time beginning with
this time, specified in ms since epoch
:param str finished_time_end: jobs with finish time ending with this
time, specified in ms since epoch
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `state`
incorrect
"""
path = '/ws/v1/history/mapreduce/jobs'
legal_states = set([s for s, _ in JobStateInternal])
if state is not None and state not in legal_states:
msg = 'Job Internal State %s is illegal' % (state,)
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('user', user),
('queue', queue),
('limit', limit),
('startedTimeBegin', started_time_begin),
('startedTimeEnd', started_time_end),
('finishedTimeBegin', finished_time_begin),
('finishedTimeEnd', finished_time_end))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def job(self, job_id):
"""
A Job resource contains information about a particular job identified
by jobid.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}'.format(jobid=job_id)
return self.request(path)
def job_attempts(self, job_id):
"""
With the job attempts API, you can obtain a collection of resources
that represent a job attempt.
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/jobattempts'.format(
jobid=job_id)
return self.request(path)
def job_conf(self, job_id):
"""
A job configuration resource contains information about the job
configuration for this job.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/conf'.format(jobid=job_id)
return self.request(path)
def job_tasks(self, job_id, type=None):
"""
With the tasks API, you can obtain a collection of resources that
represent a task within a job.
:param str job_id: The job id
:param str type: type of task, valid values are m or r. m for map
task or r for reduce task
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks'.format(
jobid=job_id)
# m - for map
# r - for reduce
valid_types = ['m', 'r']
if type is not None and type not in valid_types:
msg = 'Job type %s is illegal' % (type,)
raise IllegalArgumentError(msg)
params = {}
if type is not None:
params['type'] = type
return self.request(path, **params)
def job_task(self, job_id, task_id):
"""
A Task resource contains information about a particular task
within a job.
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}'.format(
jobid=job_id, taskid=task_id)
return self.request(path)
def task_counters(self, job_id, task_id):
"""
With the task counters API, you can object a collection of resources
that represent all the counters for that task.
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/counters'.format(
jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempts(self, job_id, task_id):
"""
With the task attempts API, you can obtain a collection of resources
that represent a task attempt within a job.
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts'.format(
jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempt(self, job_id, task_id, attempt_id):
"""
A Task Attempt resource contains information about a particular task
attempt within a job.
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts/{attemptid}'.format(
jobid=job_id, taskid=task_id, attemptid=attempt_id)
return self.request(path)
def task_attempt_counters(self, job_id, task_id, attempt_id):
"""
With the task attempt counters API, you can object a collection of
resources that represent al the counters for that task attempt.
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts/{attemptid}/counters'.format(
jobid=job_id, taskid=task_id, attemptid=attempt_id)
return self.request(path)
|
toidi/hadoop-yarn-api-python-client | yarn_api_client/history_server.py | HistoryServer.job_conf | python | def job_conf(self, job_id):
path = '/ws/v1/history/mapreduce/jobs/{jobid}/conf'.format(jobid=job_id)
return self.request(path) | A job configuration resource contains information about the job
configuration for this job.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response` | train | https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/history_server.py#L124-L135 | [
"def request(self, api_path, **query_args):\n params = query_args\n api_endpoint = 'http://{}:{}{}'.format(self.address, self.port, api_path)\n\n self.logger.info('API Endpoint {}'.format(api_endpoint))\n\n self._validate_configuration()\n\n response = None\n if self.kerberos_enabled:\n fro... | class HistoryServer(BaseYarnAPI):
"""
The history server REST API's allow the user to get status on finished
applications. Currently it only supports MapReduce and provides
information on finished jobs.
If `address` argument is `None` client will try to extract `address` and
`port` from Hadoop configuration files.
:param str address: HistoryServer HTTP address
:param int port: HistoryServer HTTP port
:param int timeout: API connection timeout in seconds
:param boolean kerberos_enabled: Flag identifying is Kerberos Security has been enabled for YARN
"""
def __init__(self, address=None, port=19888, timeout=30, kerberos_enabled=False):
self.address, self.port, self.timeout, self.kerberos_enabled = address, port, timeout, kerberos_enabled
if address is None:
self.logger.debug('Get information from hadoop conf dir')
address, port = get_jobhistory_host_port()
self.address, self.port = address, port
def application_information(self):
"""
The history server information resource provides overall information
about the history server.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/info'
return self.request(path)
def jobs(self, state=None, user=None, queue=None, limit=None,
started_time_begin=None, started_time_end=None,
finished_time_begin=None, finished_time_end=None):
"""
The jobs resource provides a list of the MapReduce jobs that have
finished. It does not currently return a full list of parameters.
:param str user: user name
:param str state: the job state
:param str queue: queue name
:param str limit: total number of app objects to be returned
:param str started_time_begin: jobs with start time beginning with
this time, specified in ms since epoch
:param str started_time_end: jobs with start time ending with this
time, specified in ms since epoch
:param str finished_time_begin: jobs with finish time beginning with
this time, specified in ms since epoch
:param str finished_time_end: jobs with finish time ending with this
time, specified in ms since epoch
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `state`
incorrect
"""
path = '/ws/v1/history/mapreduce/jobs'
legal_states = set([s for s, _ in JobStateInternal])
if state is not None and state not in legal_states:
msg = 'Job Internal State %s is illegal' % (state,)
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('user', user),
('queue', queue),
('limit', limit),
('startedTimeBegin', started_time_begin),
('startedTimeEnd', started_time_end),
('finishedTimeBegin', finished_time_begin),
('finishedTimeEnd', finished_time_end))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def job(self, job_id):
"""
A Job resource contains information about a particular job identified
by jobid.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}'.format(jobid=job_id)
return self.request(path)
def job_attempts(self, job_id):
"""
With the job attempts API, you can obtain a collection of resources
that represent a job attempt.
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/jobattempts'.format(
jobid=job_id)
return self.request(path)
def job_counters(self, job_id):
"""
With the job counters API, you can object a collection of resources
that represent al the counters for that job.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/counters'.format(
jobid=job_id)
return self.request(path)
def job_tasks(self, job_id, type=None):
"""
With the tasks API, you can obtain a collection of resources that
represent a task within a job.
:param str job_id: The job id
:param str type: type of task, valid values are m or r. m for map
task or r for reduce task
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks'.format(
jobid=job_id)
# m - for map
# r - for reduce
valid_types = ['m', 'r']
if type is not None and type not in valid_types:
msg = 'Job type %s is illegal' % (type,)
raise IllegalArgumentError(msg)
params = {}
if type is not None:
params['type'] = type
return self.request(path, **params)
def job_task(self, job_id, task_id):
"""
A Task resource contains information about a particular task
within a job.
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}'.format(
jobid=job_id, taskid=task_id)
return self.request(path)
def task_counters(self, job_id, task_id):
"""
With the task counters API, you can object a collection of resources
that represent all the counters for that task.
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/counters'.format(
jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempts(self, job_id, task_id):
"""
With the task attempts API, you can obtain a collection of resources
that represent a task attempt within a job.
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts'.format(
jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempt(self, job_id, task_id, attempt_id):
"""
A Task Attempt resource contains information about a particular task
attempt within a job.
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts/{attemptid}'.format(
jobid=job_id, taskid=task_id, attemptid=attempt_id)
return self.request(path)
def task_attempt_counters(self, job_id, task_id, attempt_id):
"""
With the task attempt counters API, you can object a collection of
resources that represent al the counters for that task attempt.
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts/{attemptid}/counters'.format(
jobid=job_id, taskid=task_id, attemptid=attempt_id)
return self.request(path)
|
toidi/hadoop-yarn-api-python-client | yarn_api_client/history_server.py | HistoryServer.job_tasks | python | def job_tasks(self, job_id, type=None):
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks'.format(
jobid=job_id)
# m - for map
# r - for reduce
valid_types = ['m', 'r']
if type is not None and type not in valid_types:
msg = 'Job type %s is illegal' % (type,)
raise IllegalArgumentError(msg)
params = {}
if type is not None:
params['type'] = type
return self.request(path, **params) | With the tasks API, you can obtain a collection of resources that
represent a task within a job.
:param str job_id: The job id
:param str type: type of task, valid values are m or r. m for map
task or r for reduce task
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response` | train | https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/history_server.py#L137-L162 | [
"def request(self, api_path, **query_args):\n params = query_args\n api_endpoint = 'http://{}:{}{}'.format(self.address, self.port, api_path)\n\n self.logger.info('API Endpoint {}'.format(api_endpoint))\n\n self._validate_configuration()\n\n response = None\n if self.kerberos_enabled:\n fro... | class HistoryServer(BaseYarnAPI):
"""
The history server REST API's allow the user to get status on finished
applications. Currently it only supports MapReduce and provides
information on finished jobs.
If `address` argument is `None` client will try to extract `address` and
`port` from Hadoop configuration files.
:param str address: HistoryServer HTTP address
:param int port: HistoryServer HTTP port
:param int timeout: API connection timeout in seconds
:param boolean kerberos_enabled: Flag identifying is Kerberos Security has been enabled for YARN
"""
def __init__(self, address=None, port=19888, timeout=30, kerberos_enabled=False):
self.address, self.port, self.timeout, self.kerberos_enabled = address, port, timeout, kerberos_enabled
if address is None:
self.logger.debug('Get information from hadoop conf dir')
address, port = get_jobhistory_host_port()
self.address, self.port = address, port
def application_information(self):
"""
The history server information resource provides overall information
about the history server.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/info'
return self.request(path)
def jobs(self, state=None, user=None, queue=None, limit=None,
started_time_begin=None, started_time_end=None,
finished_time_begin=None, finished_time_end=None):
"""
The jobs resource provides a list of the MapReduce jobs that have
finished. It does not currently return a full list of parameters.
:param str user: user name
:param str state: the job state
:param str queue: queue name
:param str limit: total number of app objects to be returned
:param str started_time_begin: jobs with start time beginning with
this time, specified in ms since epoch
:param str started_time_end: jobs with start time ending with this
time, specified in ms since epoch
:param str finished_time_begin: jobs with finish time beginning with
this time, specified in ms since epoch
:param str finished_time_end: jobs with finish time ending with this
time, specified in ms since epoch
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `state`
incorrect
"""
path = '/ws/v1/history/mapreduce/jobs'
legal_states = set([s for s, _ in JobStateInternal])
if state is not None and state not in legal_states:
msg = 'Job Internal State %s is illegal' % (state,)
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('user', user),
('queue', queue),
('limit', limit),
('startedTimeBegin', started_time_begin),
('startedTimeEnd', started_time_end),
('finishedTimeBegin', finished_time_begin),
('finishedTimeEnd', finished_time_end))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def job(self, job_id):
"""
A Job resource contains information about a particular job identified
by jobid.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}'.format(jobid=job_id)
return self.request(path)
def job_attempts(self, job_id):
"""
With the job attempts API, you can obtain a collection of resources
that represent a job attempt.
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/jobattempts'.format(
jobid=job_id)
return self.request(path)
def job_counters(self, job_id):
"""
With the job counters API, you can object a collection of resources
that represent al the counters for that job.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/counters'.format(
jobid=job_id)
return self.request(path)
def job_conf(self, job_id):
"""
A job configuration resource contains information about the job
configuration for this job.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/conf'.format(jobid=job_id)
return self.request(path)
def job_task(self, job_id, task_id):
"""
A Task resource contains information about a particular task
within a job.
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}'.format(
jobid=job_id, taskid=task_id)
return self.request(path)
def task_counters(self, job_id, task_id):
"""
With the task counters API, you can object a collection of resources
that represent all the counters for that task.
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/counters'.format(
jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempts(self, job_id, task_id):
"""
With the task attempts API, you can obtain a collection of resources
that represent a task attempt within a job.
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts'.format(
jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempt(self, job_id, task_id, attempt_id):
"""
A Task Attempt resource contains information about a particular task
attempt within a job.
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts/{attemptid}'.format(
jobid=job_id, taskid=task_id, attemptid=attempt_id)
return self.request(path)
def task_attempt_counters(self, job_id, task_id, attempt_id):
"""
With the task attempt counters API, you can object a collection of
resources that represent al the counters for that task attempt.
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts/{attemptid}/counters'.format(
jobid=job_id, taskid=task_id, attemptid=attempt_id)
return self.request(path)
|
toidi/hadoop-yarn-api-python-client | yarn_api_client/history_server.py | HistoryServer.task_attempt | python | def task_attempt(self, job_id, task_id, attempt_id):
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts/{attemptid}'.format(
jobid=job_id, taskid=task_id, attemptid=attempt_id)
return self.request(path) | A Task Attempt resource contains information about a particular task
attempt within a job.
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response` | train | https://github.com/toidi/hadoop-yarn-api-python-client/blob/d245bd41808879be6637acfd7460633c0c7dfdd6/yarn_api_client/history_server.py#L209-L223 | [
"def request(self, api_path, **query_args):\n params = query_args\n api_endpoint = 'http://{}:{}{}'.format(self.address, self.port, api_path)\n\n self.logger.info('API Endpoint {}'.format(api_endpoint))\n\n self._validate_configuration()\n\n response = None\n if self.kerberos_enabled:\n fro... | class HistoryServer(BaseYarnAPI):
"""
The history server REST API's allow the user to get status on finished
applications. Currently it only supports MapReduce and provides
information on finished jobs.
If `address` argument is `None` client will try to extract `address` and
`port` from Hadoop configuration files.
:param str address: HistoryServer HTTP address
:param int port: HistoryServer HTTP port
:param int timeout: API connection timeout in seconds
:param boolean kerberos_enabled: Flag identifying is Kerberos Security has been enabled for YARN
"""
def __init__(self, address=None, port=19888, timeout=30, kerberos_enabled=False):
self.address, self.port, self.timeout, self.kerberos_enabled = address, port, timeout, kerberos_enabled
if address is None:
self.logger.debug('Get information from hadoop conf dir')
address, port = get_jobhistory_host_port()
self.address, self.port = address, port
def application_information(self):
"""
The history server information resource provides overall information
about the history server.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/info'
return self.request(path)
def jobs(self, state=None, user=None, queue=None, limit=None,
started_time_begin=None, started_time_end=None,
finished_time_begin=None, finished_time_end=None):
"""
The jobs resource provides a list of the MapReduce jobs that have
finished. It does not currently return a full list of parameters.
:param str user: user name
:param str state: the job state
:param str queue: queue name
:param str limit: total number of app objects to be returned
:param str started_time_begin: jobs with start time beginning with
this time, specified in ms since epoch
:param str started_time_end: jobs with start time ending with this
time, specified in ms since epoch
:param str finished_time_begin: jobs with finish time beginning with
this time, specified in ms since epoch
:param str finished_time_end: jobs with finish time ending with this
time, specified in ms since epoch
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
:raises yarn_api_client.errors.IllegalArgumentError: if `state`
incorrect
"""
path = '/ws/v1/history/mapreduce/jobs'
legal_states = set([s for s, _ in JobStateInternal])
if state is not None and state not in legal_states:
msg = 'Job Internal State %s is illegal' % (state,)
raise IllegalArgumentError(msg)
loc_args = (
('state', state),
('user', user),
('queue', queue),
('limit', limit),
('startedTimeBegin', started_time_begin),
('startedTimeEnd', started_time_end),
('finishedTimeBegin', finished_time_begin),
('finishedTimeEnd', finished_time_end))
params = self.construct_parameters(loc_args)
return self.request(path, **params)
def job(self, job_id):
"""
A Job resource contains information about a particular job identified
by jobid.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}'.format(jobid=job_id)
return self.request(path)
def job_attempts(self, job_id):
"""
With the job attempts API, you can obtain a collection of resources
that represent a job attempt.
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/jobattempts'.format(
jobid=job_id)
return self.request(path)
def job_counters(self, job_id):
"""
With the job counters API, you can object a collection of resources
that represent al the counters for that job.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/counters'.format(
jobid=job_id)
return self.request(path)
def job_conf(self, job_id):
"""
A job configuration resource contains information about the job
configuration for this job.
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/conf'.format(jobid=job_id)
return self.request(path)
def job_tasks(self, job_id, type=None):
"""
With the tasks API, you can obtain a collection of resources that
represent a task within a job.
:param str job_id: The job id
:param str type: type of task, valid values are m or r. m for map
task or r for reduce task
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks'.format(
jobid=job_id)
# m - for map
# r - for reduce
valid_types = ['m', 'r']
if type is not None and type not in valid_types:
msg = 'Job type %s is illegal' % (type,)
raise IllegalArgumentError(msg)
params = {}
if type is not None:
params['type'] = type
return self.request(path, **params)
def job_task(self, job_id, task_id):
"""
A Task resource contains information about a particular task
within a job.
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}'.format(
jobid=job_id, taskid=task_id)
return self.request(path)
def task_counters(self, job_id, task_id):
"""
With the task counters API, you can object a collection of resources
that represent all the counters for that task.
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/counters'.format(
jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempts(self, job_id, task_id):
"""
With the task attempts API, you can obtain a collection of resources
that represent a task attempt within a job.
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts'.format(
jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempt_counters(self, job_id, task_id, attempt_id):
"""
With the task attempt counters API, you can object a collection of
resources that represent al the counters for that task attempt.
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts/{attemptid}/counters'.format(
jobid=job_id, taskid=task_id, attemptid=attempt_id)
return self.request(path)
|
NiklasRosenstein/myo-python | myo/macaddr.py | encode | python | def encode(value):
if value > MAX_VALUE:
raise ValueError('value {!r} exceeds MAC address range'.format(value))
if value < 0:
raise ValueError('value must not be negative')
# todo: convert to the right byte order. the resulting
# mac address is reversed on my machine compared to the
# mac address displayed by the hello-myo SDK sample.
# See issue #7
string = ('%x' % value).rjust(12, '0')
assert len(string) == 12
result = ':'.join(''.join(pair) for pair in zip(*[iter(string)]*2))
return result.upper() | Encodes the number *value* to a MAC address ASCII string in binary form.
Raises a #ValueError if *value* is a negative number or exceeds the MAC
address range. | train | https://github.com/NiklasRosenstein/myo-python/blob/89a7480f8058061da7a3dd98ccec57a6b134ddf3/myo/macaddr.py#L28-L49 | null | # The MIT License (MIT)
#
# Copyright (c) 2015-2018 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import six
MAX_VALUE = (16 ** 12 - 1)
def decode(bstr):
"""
Decodes an ASCII encoded binary MAC address tring into a number.
"""
bstr = bstr.replace(b':', b'')
if len(bstr) != 12:
raise ValueError('not a valid MAC address: {!r}'.format(bstr))
try:
return int(bstr, 16)
except ValueError:
raise ValueError('not a valid MAC address: {!r}'.format(bstr))
class MacAddress(object):
"""
Represents a MAC address. Instances of this class are immutable.
"""
def __init__(self, value):
if isinstance(value, six.integer_types):
if value < 0 or value > MAX_VALUE:
raise ValueError('value {!r} out of MAC address range'.format(value))
elif isinstance(value, six.string_to_int):
if isinstance(value, six.text_type):
value = value.encode('ascii')
value = decode(value)
else:
msg = 'expected string, bytes or int for MacAddress, got {}'
return TypeError(msg.format(type(value).__name__))
self._value = value
self._string = None
def __str__(self):
if self._string is None:
self._string = encode(self._value)
return self._string
def __repr__(self):
return '<MAC {}>'.format(self)
@property
def value(self):
return self._value
|
NiklasRosenstein/myo-python | myo/macaddr.py | decode | python | def decode(bstr):
bstr = bstr.replace(b':', b'')
if len(bstr) != 12:
raise ValueError('not a valid MAC address: {!r}'.format(bstr))
try:
return int(bstr, 16)
except ValueError:
raise ValueError('not a valid MAC address: {!r}'.format(bstr)) | Decodes an ASCII encoded binary MAC address tring into a number. | train | https://github.com/NiklasRosenstein/myo-python/blob/89a7480f8058061da7a3dd98ccec57a6b134ddf3/myo/macaddr.py#L52-L64 | null | # The MIT License (MIT)
#
# Copyright (c) 2015-2018 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import six
MAX_VALUE = (16 ** 12 - 1)
def encode(value):
"""
Encodes the number *value* to a MAC address ASCII string in binary form.
Raises a #ValueError if *value* is a negative number or exceeds the MAC
address range.
"""
if value > MAX_VALUE:
raise ValueError('value {!r} exceeds MAC address range'.format(value))
if value < 0:
raise ValueError('value must not be negative')
# todo: convert to the right byte order. the resulting
# mac address is reversed on my machine compared to the
# mac address displayed by the hello-myo SDK sample.
# See issue #7
string = ('%x' % value).rjust(12, '0')
assert len(string) == 12
result = ':'.join(''.join(pair) for pair in zip(*[iter(string)]*2))
return result.upper()
class MacAddress(object):
"""
Represents a MAC address. Instances of this class are immutable.
"""
def __init__(self, value):
if isinstance(value, six.integer_types):
if value < 0 or value > MAX_VALUE:
raise ValueError('value {!r} out of MAC address range'.format(value))
elif isinstance(value, six.string_to_int):
if isinstance(value, six.text_type):
value = value.encode('ascii')
value = decode(value)
else:
msg = 'expected string, bytes or int for MacAddress, got {}'
return TypeError(msg.format(type(value).__name__))
self._value = value
self._string = None
def __str__(self):
if self._string is None:
self._string = encode(self._value)
return self._string
def __repr__(self):
return '<MAC {}>'.format(self)
@property
def value(self):
return self._value
|
NiklasRosenstein/myo-python | myo/_ffi.py | init | python | def init(lib_name=None, bin_path=None, sdk_path=None):
if sum(bool(x) for x in [lib_name, bin_path, sdk_path]) > 1:
raise ValueError('expected zero or one arguments')
if sdk_path:
if sys.platform.startswith('win32'):
bin_path = os.path.join(sdk_path, 'bin')
elif sys.platform.startswith('darwin'):
bin_path = os.path.join(sdk_path, 'myo.framework')
else:
raise RuntimeError('unsupported platform: {!r}'.format(sys.platform))
if bin_path:
lib_name = os.path.join(bin_path, _getdlname())
if not lib_name:
lib_name = _getdlname()
global libmyo
libmyo = ffi.dlopen(lib_name) | Initialize the Myo SDK by loading the libmyo shared library. With no
arguments, libmyo must be on your `PATH` or `LD_LIBRARY_PATH`.
You can specify the exact path to libmyo with *lib_name*. Alternatively,
you can specify the binaries directory that contains libmyo with *bin_path*.
Finally, you can also pass the path to the Myo SDK root directory and it
will figure out the path to libmyo by itself. | train | https://github.com/NiklasRosenstein/myo-python/blob/89a7480f8058061da7a3dd98ccec57a6b134ddf3/myo/_ffi.py#L209-L236 | null | # The MIT License (MIT)
#
# Copyright (c) 2015-2018 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import contextlib
import cffi
import os
import pkgutil
import re
import threading
import six
import sys
from .macaddr import MacAddress
from .math import Quaternion, Vector
try:
from nr.types.enum import Enumeration
except ImportError:
from nr.enum import Enumeration
##
# Exceptions
##
class Error(Exception):
"""
Base class for errors and exceptions in the myo library.
"""
class ResultError(Error):
"""
Raised if the result of an operation with the Myo library was anything
but successful.
"""
def __init__(self, kind, message):
self.kind = kind
self.message = message
def __str__(self):
return str((self.kind, self.message))
class InvalidOperation(Error):
"""
Raised if an invalid operation is performed, for example if you attempt to
read the firmware version in any event other than *paired* and *connect*.
"""
##
# Enumerations
##
class Result(Enumeration):
__fallback__ = True
success = 0
error = 1
error_invalid_argument = 2
error_runtime = 3
class VibrationType(Enumeration):
__fallback__ = True
short = 0
medium = 1
long = 2
class StreamEmg(Enumeration):
__fallback__ = True
disabled = 0
enabled = 1
class Pose(Enumeration):
__fallback__ = True
num_poses = Enumeration.Data(6)
rest = 0
fist = 1
wave_in = 2
wave_out = 3
fingers_spread = 4
double_tap = 5
class EventType(Enumeration):
__fallback__ = True
paired = 0
unpaired = 1
connected = 2
disconnected = 3
arm_synced = 4
arm_unsynced = 5
orientation = 6
pose = 7
rssi = 8
unlocked = 9
locked = 10
emg = 11
battery_level = 12
warmup_completed = 13
class HandlerResult(Enumeration):
__fallback__ = True
continue_ = 0
stop = 1
class LockingPolicy(Enumeration):
__fallback__ = True
none = 0 #: Pose events are always sent.
standard = 1 #: (default) Pose events are not sent while a Myo is locked.
class Arm(Enumeration):
__fallback__ = True
right = 0
left = 1
unknown = 2
class XDirection(Enumeration):
__fallback__ = True
toward_wrist = 0
toward_elbow = 1
unknown = 2
class UnlockType(Enumeration):
__fallback__ = True
timed = 0
hold = 1
class UserActionType(Enumeration):
__fallback__ = True
single = 0
class WarmupState(Enumeration):
__fallback__ = True
unknown = 0
cold = 1
warm = 2
class WarmupResult(Enumeration):
__fallback__ = True
unknown = 0
success = 1
failed_timeout = 2
##
# CFFI
##
def _getffi():
string = pkgutil.get_data(__name__, 'libmyo.h').decode('utf8')
string = string.replace('\r\n', '\n')
# Remove stuff that cffi can not parse.
string = re.sub('^\s*#.*$', '', string, flags=re.M)
string = string.replace('LIBMYO_EXPORT', '')
string = string.replace('extern "C" {', '')
string = string.replace('} // extern "C"', '')
ffi = cffi.FFI()
ffi.cdef(string)
return ffi
ffi = _getffi()
libmyo = None
def _getdlname():
arch = 32 if sys.maxsize <= 2 ** 32 else 64
if sys.platform.startswith('win32'):
return 'myo{}.dll'.format(arch)
elif sys.platform.startswith('darwin'):
return 'myo'
else:
raise RuntimeError('unsupported platform: {!r}'.format(sys.platform))
class _BaseWrapper(object):
def __init__(self, handle):
self._handle = handle
@property
def handle(self):
return self._handle
class ErrorDetails(_BaseWrapper):
"""
Wraps Myo error details information.
"""
def __init__(self):
super(ErrorDetails, self).__init__(ffi.new('libmyo_hub_t*'))
def __del__(self):
if self._handle[0]:
libmyo.libmyo_free_error_details(self._handle[0])
@property
def kind(self):
if self._handle[0]:
result = Result(libmyo.libmyo_error_kind(self._handle[0]))
else:
result = Result.success
return result
@property
def message(self):
if self._handle[0]:
return ffi.string(libmyo.libmyo_error_cstring(self._handle[0]))
else:
return ''
@property
def handle(self):
return self._handle
def raise_for_kind(self):
kind = self.kind
if kind != Result.success:
raise ResultError(kind, self.message)
class Event(_BaseWrapper):
def __init__(self, handle):
super(Event, self).__init__(handle)
self._type = EventType(libmyo.libmyo_event_get_type(self._handle))
def __repr__(self):
return 'Event(type={!r}, timestamp={!r}, mac_address={!r})'.format(
self.type, self.timestamp, self.mac_address)
@property
def type(self):
return self._type
@property
def timestamp(self):
return libmyo.libmyo_event_get_timestamp(self._handle)
@property
def device(self):
return Device(libmyo.libmyo_event_get_myo(self._handle))
@property
def device_name(self):
return str(String(libmyo.libmyo_event_get_myo_name(self._handle)))
@property
def mac_address(self):
if self.type == EventType.emg:
return None
return MacAddress(libmyo.libmyo_event_get_mac_address(self._handle))
@property
def firmware_version(self):
return tuple(libmyo.libmyo_event_get_firmware_version(self._handle, x)
for x in [0, 1, 2, 3])
@property
def arm(self):
if self.type != EventType.arm_synced:
raise InvalidOperation()
return Arm(libmyo.libmyo_event_get_arm(self._handle))
@property
def x_direction(self):
if self.type != EventType.arm_synced:
raise InvalidOperation()
return XDirection(libmyo.libmyo_event_get_x_direction(self._handle))
@property
def warmup_state(self):
if self.type != EventType.arm_synced:
raise InvalidOperation()
return WarmupState(libmyo.libmyo_event_get_warmup_state(self._handle))
@property
def warmup_result(self):
if self.type != EventType.warmup_completed:
raise InvalidOperation()
return WarmupResult(libmyo.libmyo_event_get_warmup_result(self._handle))
@property
def rotation_on_arm(self):
if self.type != EventType.arm_synced:
raise InvalidOperation()
return libmyo.libmyo_event_get_rotation_on_arm(self._handle)
@property
def orientation(self):
if self.type != EventType.orientation:
raise InvalidOperation()
vals = (libmyo.libmyo_event_get_orientation(self._handle, i)
for i in [0, 1, 2, 3])
return Quaternion(*vals)
@property
def acceleration(self):
if self.type != EventType.orientation:
raise InvalidOperation()
vals = (libmyo.libmyo_event_get_accelerometer(self._handle, i)
for i in [0, 1, 2])
return Vector(*vals)
@property
def gyroscope(self):
if self.type != EventType.orientation:
raise InvalidOperation()
vals = (libmyo.libmyo_event_get_gyroscope(self._handle, i)
for i in [0, 1, 2])
return Vector(*vals)
@property
def pose(self):
if self.type != EventType.pose:
raise InvalidOperation()
return Pose(libmyo.libmyo_event_get_pose(self._handle))
@property
def rssi(self):
if self.type != EventType.rssi:
raise InvalidOperation()
return libmyo.libmyo_event_get_rssi(self._handle)
@property
def battery_level(self):
if self.type != EventType.battery_level:
raise InvalidOperation()
return libmyo.libmyo_event_get_battery_level(self._handle)
@property
def emg(self):
if self.type != EventType.emg:
raise InvalidOperation()
return [libmyo.libmyo_event_get_emg(self._handle, i) for i in range(8)]
class Device(_BaseWrapper):
# libmyo_get_mac_address() is not in the Myo SDK 0.9.0 DLL.
#@property
#def mac_address(self):
# return MacAddress(libmyo.libmyo_get_mac_address(self._handle))
def vibrate(self, type=VibrationType.medium):
if not isinstance(type, VibrationType):
raise TypeError('expected VibrationType')
error = ErrorDetails()
libmyo.libmyo_vibrate(self._handle, int(type), error.handle)
return error.raise_for_kind()
def stream_emg(self, type):
if type is True: type = StreamEmg.enabled
elif type is False: type = StreamEmg.disabled
elif not isinstance(type, StreamEmg):
raise TypeError('expected bool or StreamEmg')
error = ErrorDetails()
libmyo.libmyo_set_stream_emg(self._handle, int(type), error.handle)
error.raise_for_kind()
def request_rssi(self):
error = ErrorDetails()
libmyo.libmyo_request_rssi(self._handle, error.handle)
error.raise_for_kind()
def request_battery_level(self):
error = ErrorDetails()
libmyo.libmyo_request_battery_level(self._handle, error.handle)
error.raise_for_kind()
def unlock(self, type=UnlockType.hold):
if not isinstance(type, UnlockType):
raise TypeError('expected UnlockType')
error = ErrorDetails()
libmyo.libmyo_myo_unlock(self._handle, int(type), error.handle)
error.raise_for_kind()
def lock(self):
error = ErrorDetails()
libmyo.libmyo_myo_lock(self._handle, error.handle)
error.raise_for_kind()
def notify_user_action(self, type=UserActionType.single):
if not isinstance(type, UserActionType):
raise TypeError('expected UserActionType')
error = ErrorDetails()
libmyo.libmyo_myo_notify_user_action(self._handle, int(type), error.handle)
error.raise_for_kind()
class String(_BaseWrapper):
def __str__(self):
return ffi.string(libmyo.libmyo_string_c_str(self._handle)).decode('utf8')
def __del__(self):
libmyo.libmyo_string_free(self._handle)
class Hub(_BaseWrapper):
"""
Low-level wrapper for a Myo Hub object.
"""
def __init__(self, application_identifier='com.niklasrosenstein.myo-python'):
super(Hub, self).__init__(ffi.new('libmyo_hub_t*'))
error = ErrorDetails()
libmyo.libmyo_init_hub(self._handle, application_identifier.encode('ascii'), error.handle)
error.raise_for_kind()
self.locking_policy = LockingPolicy.none
self._lock = threading.Lock()
self._running = False
self._stop_requested = False
self._stopped = False
def __del__(self):
if self._handle[0]:
error = ErrorDetails()
libmyo.libmyo_shutdown_hub(self._handle[0], error.handle)
error.raise_for_kind()
@property
def handle(self):
return self._handle
@property
def locking_policy(self):
return self._locking_policy
@locking_policy.setter
def locking_policy(self, policy):
if not isinstance(policy, LockingPolicy):
raise TypeError('expected LockingPolicy')
error = ErrorDetails()
libmyo.libmyo_set_locking_policy(self._handle[0], int(policy), error.handle)
error.raise_for_kind()
@property
def running(self):
with self._lock:
return self._running
def run(self, handler, duration_ms):
"""
Runs the *handler* function for *duration_ms* milliseconds. The function
must accept exactly one argument which is an #Event object. The handler
must return either a #HandlerResult value, #False, #True or #None, whereas
#False represents #HandlerResult.stop and #True and #None represent
#HandlerResult.continue_.
If the run did not complete due to the handler returning #HandlerResult.stop
or #False or the procedure was cancelled via #Hub.stop(), this function
returns #False. If the full *duration_ms* completed, #True is returned.
This function blocks the caller until either *duration_ms* passed, the
handler returned #HandlerResult.stop or #False or #Hub.stop() was called.
"""
if not callable(handler):
if hasattr(handler, 'on_event'):
handler = handler.on_event
else:
raise TypeError('expected callable or DeviceListener')
with self._lock:
if self._running:
raise RuntimeError('a handler is already running in the Hub')
self._running = True
self._stop_requested = False
self._stopped = False
exc_box = []
def callback_on_error(*exc_info):
exc_box.append(exc_info)
with self._lock:
self._stopped = True
return HandlerResult.stop
def callback(_, event):
with self._lock:
if self._stop_requested:
self._stopped = True
return HandlerResult.stop
result = handler(Event(event))
if result is None or result is True:
result = HandlerResult.continue_
elif result is False:
result = HandlerResult.stop
else:
result = HandlerResult(result)
if result == HandlerResult.stop:
with self._lock:
self._stopped = True
return result
cdecl = 'libmyo_handler_result_t(void*, libmyo_event_t)'
callback = ffi.callback(cdecl, callback, onerror=callback_on_error)
try:
error = ErrorDetails()
libmyo.libmyo_run(self._handle[0], duration_ms, callback, ffi.NULL, error.handle)
error.raise_for_kind()
if exc_box:
six.reraise(*exc_box[0])
finally:
with self._lock:
self._running = False
result = not self._stopped
return result
def run_forever(self, handler, duration_ms=500):
while self.run(handler, duration_ms):
if self._stop_requested:
break
@contextlib.contextmanager
def run_in_background(self, handler, duration_ms=500):
thread = threading.Thread(target=lambda: self.run_forever(handler, duration_ms))
thread.start()
try:
yield thread
finally:
self.stop()
def stop(self):
with self._lock:
self._stop_requested = True
__all__ = [
'Error', 'ResultError', 'InvalidOperation',
'Result', 'VibrationType', 'StreamEmg', 'Pose', 'EventType', 'LockingPolicy',
'Arm', 'XDirection', 'UnlockType', 'UserActionType', 'WarmupState',
'WarmupResult',
'Event', 'Device', 'Hub', 'init'
]
|
NiklasRosenstein/myo-python | myo/_ffi.py | Hub.run | python | def run(self, handler, duration_ms):
if not callable(handler):
if hasattr(handler, 'on_event'):
handler = handler.on_event
else:
raise TypeError('expected callable or DeviceListener')
with self._lock:
if self._running:
raise RuntimeError('a handler is already running in the Hub')
self._running = True
self._stop_requested = False
self._stopped = False
exc_box = []
def callback_on_error(*exc_info):
exc_box.append(exc_info)
with self._lock:
self._stopped = True
return HandlerResult.stop
def callback(_, event):
with self._lock:
if self._stop_requested:
self._stopped = True
return HandlerResult.stop
result = handler(Event(event))
if result is None or result is True:
result = HandlerResult.continue_
elif result is False:
result = HandlerResult.stop
else:
result = HandlerResult(result)
if result == HandlerResult.stop:
with self._lock:
self._stopped = True
return result
cdecl = 'libmyo_handler_result_t(void*, libmyo_event_t)'
callback = ffi.callback(cdecl, callback, onerror=callback_on_error)
try:
error = ErrorDetails()
libmyo.libmyo_run(self._handle[0], duration_ms, callback, ffi.NULL, error.handle)
error.raise_for_kind()
if exc_box:
six.reraise(*exc_box[0])
finally:
with self._lock:
self._running = False
result = not self._stopped
return result | Runs the *handler* function for *duration_ms* milliseconds. The function
must accept exactly one argument which is an #Event object. The handler
must return either a #HandlerResult value, #False, #True or #None, whereas
#False represents #HandlerResult.stop and #True and #None represent
#HandlerResult.continue_.
If the run did not complete due to the handler returning #HandlerResult.stop
or #False or the procedure was cancelled via #Hub.stop(), this function
returns #False. If the full *duration_ms* completed, #True is returned.
This function blocks the caller until either *duration_ms* passed, the
handler returned #HandlerResult.stop or #False or #Hub.stop() was called. | train | https://github.com/NiklasRosenstein/myo-python/blob/89a7480f8058061da7a3dd98ccec57a6b134ddf3/myo/_ffi.py#L507-L577 | [
"def raise_for_kind(self):\n kind = self.kind\n if kind != Result.success:\n raise ResultError(kind, self.message)\n"
] | class Hub(_BaseWrapper):
"""
Low-level wrapper for a Myo Hub object.
"""
def __init__(self, application_identifier='com.niklasrosenstein.myo-python'):
super(Hub, self).__init__(ffi.new('libmyo_hub_t*'))
error = ErrorDetails()
libmyo.libmyo_init_hub(self._handle, application_identifier.encode('ascii'), error.handle)
error.raise_for_kind()
self.locking_policy = LockingPolicy.none
self._lock = threading.Lock()
self._running = False
self._stop_requested = False
self._stopped = False
def __del__(self):
if self._handle[0]:
error = ErrorDetails()
libmyo.libmyo_shutdown_hub(self._handle[0], error.handle)
error.raise_for_kind()
@property
def handle(self):
return self._handle
@property
def locking_policy(self):
return self._locking_policy
@locking_policy.setter
def locking_policy(self, policy):
if not isinstance(policy, LockingPolicy):
raise TypeError('expected LockingPolicy')
error = ErrorDetails()
libmyo.libmyo_set_locking_policy(self._handle[0], int(policy), error.handle)
error.raise_for_kind()
@property
def running(self):
with self._lock:
return self._running
def run_forever(self, handler, duration_ms=500):
while self.run(handler, duration_ms):
if self._stop_requested:
break
@contextlib.contextmanager
def run_in_background(self, handler, duration_ms=500):
thread = threading.Thread(target=lambda: self.run_forever(handler, duration_ms))
thread.start()
try:
yield thread
finally:
self.stop()
def stop(self):
with self._lock:
self._stop_requested = True
|
NiklasRosenstein/myo-python | myo/_device_listener.py | ApiDeviceListener.wait_for_single_device | python | def wait_for_single_device(self, timeout=None, interval=0.5):
timer = TimeoutManager(timeout)
with self._cond:
# As long as there are no Myo's connected, wait until we
# get notified about a change.
while not timer.check():
# Check if we found a Myo that is connected.
for device in self._devices.values():
if device.connected:
return device
self._cond.wait(timer.remainder(interval))
return None | Waits until a Myo is was paired **and** connected with the Hub and returns
it. If the *timeout* is exceeded, returns None. This function will not
return a Myo that is only paired but not connected.
# Parameters
timeout: The maximum time to wait for a device.
interval: The interval at which the function should exit sleeping. We can
not sleep endlessly, otherwise the main thread can not be exit, eg.
through a KeyboardInterrupt. | train | https://github.com/NiklasRosenstein/myo-python/blob/89a7480f8058061da7a3dd98ccec57a6b134ddf3/myo/_device_listener.py#L218-L242 | [
"def check(self):\n \"\"\"\n Returns #True if the timeout is exceeded.\n \"\"\"\n\n if self.value is None:\n return False\n return (time.clock() - self.start) >= self.value\n"
] | class ApiDeviceListener(DeviceListener):
def __init__(self, condition_class=threading.Condition):
self._condition_class = condition_class
self._cond = condition_class()
self._devices = {}
@property
def devices(self):
with self._cond:
return list(self._devices.values())
@property
def connected_devices(self):
with self._cond:
return [x for x in self._devices.values() if x.connected]
def on_event(self, event):
with self._cond:
if event.type == EventType.paired:
device = DeviceProxy(event.device, event.timestamp,
event.firmware_version, self._condition_class)
self._devices[device._device.handle] = device
self._cond.notify_all()
return
else:
try:
if event.type == EventType.unpaired:
device = self._devices.pop(event.device.handle)
else:
device = self._devices[event.device.handle]
except KeyError:
message = 'Myo device not in the device list ({})'
warnings.warn(message.format(event), RuntimeWarning)
return
if event.type == EventType.unpaired:
with device._cond:
device._unpair_time = event.timestamp
self._cond.notify_all()
with device._cond:
if event.type == EventType.connected:
device._connect_time = event.timestamp
elif event.type == EventType.disconnected:
device._disconnect_time = event.timestamp
elif event.type == EventType.emg:
device._emg = event.emg
elif event.type == EventType.arm_synced:
device._arm = event.arm
device._x_direction = event.x_direction
elif event.type == EventType.rssi:
device._rssi = event.rssi
elif event.type == EventType.battery_level:
device._battery_level = event.battery_level
elif event.type == EventType.pose:
device._pose = event.pose
elif event.type == EventType.orientation:
device._orientation_update_index += 1
device._orientation = event.orientation
device._gyroscope = event.gyroscope
device._acceleration = event.acceleration
|
NiklasRosenstein/myo-python | myo/utils.py | TimeInterval.check | python | def check(self):
if self.value is None:
return True
return (time.clock() - self.start) >= self.value | Returns #True if the time interval has passed. | train | https://github.com/NiklasRosenstein/myo-python/blob/89a7480f8058061da7a3dd98ccec57a6b134ddf3/myo/utils.py#L37-L44 | null | class TimeInterval(object):
"""
A helper class to keep track of a time interval.
"""
def __init__(self, value, value_on_reset=None):
self.value = value
self.value_on_reset = value_on_reset
self.start = time.clock()
def reset(self, value=None):
"""
Resets the start time of the interval to now or the specified value.
"""
if value is None:
value = time.clock()
self.start = value
if self.value_on_reset:
self.value = self.value_on_reset
def check_and_reset(self, value=None):
"""
Combination of #check() and #reset().
"""
if self.check():
self.reset(value)
return True
return False
|
NiklasRosenstein/myo-python | myo/utils.py | TimeInterval.reset | python | def reset(self, value=None):
if value is None:
value = time.clock()
self.start = value
if self.value_on_reset:
self.value = self.value_on_reset | Resets the start time of the interval to now or the specified value. | train | https://github.com/NiklasRosenstein/myo-python/blob/89a7480f8058061da7a3dd98ccec57a6b134ddf3/myo/utils.py#L46-L55 | null | class TimeInterval(object):
"""
A helper class to keep track of a time interval.
"""
def __init__(self, value, value_on_reset=None):
self.value = value
self.value_on_reset = value_on_reset
self.start = time.clock()
def check(self):
"""
Returns #True if the time interval has passed.
"""
if self.value is None:
return True
return (time.clock() - self.start) >= self.value
def check_and_reset(self, value=None):
"""
Combination of #check() and #reset().
"""
if self.check():
self.reset(value)
return True
return False
|
NiklasRosenstein/myo-python | myo/utils.py | TimeInterval.check_and_reset | python | def check_and_reset(self, value=None):
if self.check():
self.reset(value)
return True
return False | Combination of #check() and #reset(). | train | https://github.com/NiklasRosenstein/myo-python/blob/89a7480f8058061da7a3dd98ccec57a6b134ddf3/myo/utils.py#L57-L65 | [
"def check(self):\n \"\"\"\n Returns #True if the time interval has passed.\n \"\"\"\n\n if self.value is None:\n return True\n return (time.clock() - self.start) >= self.value\n"
] | class TimeInterval(object):
"""
A helper class to keep track of a time interval.
"""
def __init__(self, value, value_on_reset=None):
self.value = value
self.value_on_reset = value_on_reset
self.start = time.clock()
def check(self):
"""
Returns #True if the time interval has passed.
"""
if self.value is None:
return True
return (time.clock() - self.start) >= self.value
def reset(self, value=None):
"""
Resets the start time of the interval to now or the specified value.
"""
if value is None:
value = time.clock()
self.start = value
if self.value_on_reset:
self.value = self.value_on_reset
|
NiklasRosenstein/myo-python | myo/utils.py | TimeoutManager.check | python | def check(self):
if self.value is None:
return False
return (time.clock() - self.start) >= self.value | Returns #True if the timeout is exceeded. | train | https://github.com/NiklasRosenstein/myo-python/blob/89a7480f8058061da7a3dd98ccec57a6b134ddf3/myo/utils.py#L70-L77 | null | class TimeoutManager(TimeInterval):
def remainder(self, max_value=None):
"""
Returns the time remaining for the timeout, or *max_value* if that
remainder is larger.
"""
if self.value is None:
return max_value
remainder = self.value - (time.clock() - self.start)
if remainder < 0.0:
return 0.0
elif max_value is not None and remainder > max_value:
return max_value
else:
return remainder
|
NiklasRosenstein/myo-python | myo/utils.py | TimeoutManager.remainder | python | def remainder(self, max_value=None):
if self.value is None:
return max_value
remainder = self.value - (time.clock() - self.start)
if remainder < 0.0:
return 0.0
elif max_value is not None and remainder > max_value:
return max_value
else:
return remainder | Returns the time remaining for the timeout, or *max_value* if that
remainder is larger. | train | https://github.com/NiklasRosenstein/myo-python/blob/89a7480f8058061da7a3dd98ccec57a6b134ddf3/myo/utils.py#L79-L93 | null | class TimeoutManager(TimeInterval):
def check(self):
"""
Returns #True if the timeout is exceeded.
"""
if self.value is None:
return False
return (time.clock() - self.start) >= self.value
|
NiklasRosenstein/myo-python | myo/math.py | Vector.normalized | python | def normalized(self):
norm = self.magnitude()
return Vector(self.x / norm, self.y / norm, self.z / norm) | Returns a normalized copy of this vector. | train | https://github.com/NiklasRosenstein/myo-python/blob/89a7480f8058061da7a3dd98ccec57a6b134ddf3/myo/math.py#L102-L108 | [
"def magnitude(self):\n \"\"\"\n Return the magnitude of this vector.\n \"\"\"\n\n return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)\n"
] | class Vector(object):
"""
A three-dimensional vector.
"""
__slots__ = ('x', 'y', 'z')
def __init__(self, x, y, z):
super(Vector, self).__init__()
self.x = float(x)
self.y = float(y)
self.z = float(z)
def __mul__(self, rhs):
"""
Multiplies the vector with *rhs* which can be either a scalar
to retrieve a new Vector or another vector to compute the dot
product.
"""
if isinstance(rhs, (six.integer_types, float)):
return Vector(self.x * rhs, self.y * rhs, self.z * rhs)
else:
return self.dot(rhs)
def __add__(self, rhs):
"""
Adds *self* to *rhs* and returns a new vector.
"""
if isinstance(rhs, (six.integer_types, float)):
return Vector(self.x + rhs, self.y + rhs, self.z + rhs)
else:
return Vector(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z)
def __sub__(self, rhs):
"""
Substracts *self* from *rhs* and returns a new vector.
"""
if isinstance(rhs, (six.integer_types, float)):
return Vector(self.x - rhs, self.y - rhs, self.z - rhs)
else:
return Vector(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z)
def __iter__(self):
return iter((self.x, self.y, self.z))
def __repr__(self):
return 'Vector({0}, {1}, {2})'.format(self.x, self.y, self.z)
def __invert__(self):
"""
Returns the inversion of the vector.
"""
return Vector(-self.x, -self.y, -self.z)
def __getitem__(self, index):
return (self.x, self.y, self.z)[index]
def copy(self):
"""
Returns a shallow copy of the vector.
"""
return Vector(self.x, self.y, self.z)
def magnitude(self):
"""
Return the magnitude of this vector.
"""
return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)
def dot(self, rhs):
"""
Return the dot product of this vector and *rhs*.
"""
return self.x * rhs.x + self.y * rhs.y + self.z * rhs.z
def cross(self, rhs):
"""
Return the cross product of this vector and *rhs*.
"""
return Vector(
self.y * rhs.z - self.z * rhs.y,
self.z * rhs.x - self.x * rhs.z,
self.x * rhs.y - self.y * rhs.x)
def angle_to(self, rhs):
"""
Return the angle between this vector and *rhs* in radians.
"""
return math.acos(self.dot(rhs) / (self.magnitude() * rhs.magnitude()))
__abs__ = magnitude
|
NiklasRosenstein/myo-python | myo/math.py | Vector.dot | python | def dot(self, rhs):
return self.x * rhs.x + self.y * rhs.y + self.z * rhs.z | Return the dot product of this vector and *rhs*. | train | https://github.com/NiklasRosenstein/myo-python/blob/89a7480f8058061da7a3dd98ccec57a6b134ddf3/myo/math.py#L110-L115 | null | class Vector(object):
"""
A three-dimensional vector.
"""
__slots__ = ('x', 'y', 'z')
def __init__(self, x, y, z):
super(Vector, self).__init__()
self.x = float(x)
self.y = float(y)
self.z = float(z)
def __mul__(self, rhs):
"""
Multiplies the vector with *rhs* which can be either a scalar
to retrieve a new Vector or another vector to compute the dot
product.
"""
if isinstance(rhs, (six.integer_types, float)):
return Vector(self.x * rhs, self.y * rhs, self.z * rhs)
else:
return self.dot(rhs)
def __add__(self, rhs):
"""
Adds *self* to *rhs* and returns a new vector.
"""
if isinstance(rhs, (six.integer_types, float)):
return Vector(self.x + rhs, self.y + rhs, self.z + rhs)
else:
return Vector(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z)
def __sub__(self, rhs):
"""
Substracts *self* from *rhs* and returns a new vector.
"""
if isinstance(rhs, (six.integer_types, float)):
return Vector(self.x - rhs, self.y - rhs, self.z - rhs)
else:
return Vector(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z)
def __iter__(self):
return iter((self.x, self.y, self.z))
def __repr__(self):
return 'Vector({0}, {1}, {2})'.format(self.x, self.y, self.z)
def __invert__(self):
"""
Returns the inversion of the vector.
"""
return Vector(-self.x, -self.y, -self.z)
def __getitem__(self, index):
return (self.x, self.y, self.z)[index]
def copy(self):
"""
Returns a shallow copy of the vector.
"""
return Vector(self.x, self.y, self.z)
def magnitude(self):
"""
Return the magnitude of this vector.
"""
return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)
def normalized(self):
"""
Returns a normalized copy of this vector.
"""
norm = self.magnitude()
return Vector(self.x / norm, self.y / norm, self.z / norm)
def cross(self, rhs):
"""
Return the cross product of this vector and *rhs*.
"""
return Vector(
self.y * rhs.z - self.z * rhs.y,
self.z * rhs.x - self.x * rhs.z,
self.x * rhs.y - self.y * rhs.x)
def angle_to(self, rhs):
"""
Return the angle between this vector and *rhs* in radians.
"""
return math.acos(self.dot(rhs) / (self.magnitude() * rhs.magnitude()))
__abs__ = magnitude
|
NiklasRosenstein/myo-python | myo/math.py | Vector.cross | python | def cross(self, rhs):
return Vector(
self.y * rhs.z - self.z * rhs.y,
self.z * rhs.x - self.x * rhs.z,
self.x * rhs.y - self.y * rhs.x) | Return the cross product of this vector and *rhs*. | train | https://github.com/NiklasRosenstein/myo-python/blob/89a7480f8058061da7a3dd98ccec57a6b134ddf3/myo/math.py#L117-L125 | null | class Vector(object):
"""
A three-dimensional vector.
"""
__slots__ = ('x', 'y', 'z')
def __init__(self, x, y, z):
super(Vector, self).__init__()
self.x = float(x)
self.y = float(y)
self.z = float(z)
def __mul__(self, rhs):
"""
Multiplies the vector with *rhs* which can be either a scalar
to retrieve a new Vector or another vector to compute the dot
product.
"""
if isinstance(rhs, (six.integer_types, float)):
return Vector(self.x * rhs, self.y * rhs, self.z * rhs)
else:
return self.dot(rhs)
def __add__(self, rhs):
"""
Adds *self* to *rhs* and returns a new vector.
"""
if isinstance(rhs, (six.integer_types, float)):
return Vector(self.x + rhs, self.y + rhs, self.z + rhs)
else:
return Vector(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z)
def __sub__(self, rhs):
"""
Substracts *self* from *rhs* and returns a new vector.
"""
if isinstance(rhs, (six.integer_types, float)):
return Vector(self.x - rhs, self.y - rhs, self.z - rhs)
else:
return Vector(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z)
def __iter__(self):
return iter((self.x, self.y, self.z))
def __repr__(self):
return 'Vector({0}, {1}, {2})'.format(self.x, self.y, self.z)
def __invert__(self):
"""
Returns the inversion of the vector.
"""
return Vector(-self.x, -self.y, -self.z)
def __getitem__(self, index):
return (self.x, self.y, self.z)[index]
def copy(self):
"""
Returns a shallow copy of the vector.
"""
return Vector(self.x, self.y, self.z)
def magnitude(self):
"""
Return the magnitude of this vector.
"""
return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)
def normalized(self):
"""
Returns a normalized copy of this vector.
"""
norm = self.magnitude()
return Vector(self.x / norm, self.y / norm, self.z / norm)
def dot(self, rhs):
"""
Return the dot product of this vector and *rhs*.
"""
return self.x * rhs.x + self.y * rhs.y + self.z * rhs.z
def angle_to(self, rhs):
"""
Return the angle between this vector and *rhs* in radians.
"""
return math.acos(self.dot(rhs) / (self.magnitude() * rhs.magnitude()))
__abs__ = magnitude
|
NiklasRosenstein/myo-python | myo/math.py | Vector.angle_to | python | def angle_to(self, rhs):
return math.acos(self.dot(rhs) / (self.magnitude() * rhs.magnitude())) | Return the angle between this vector and *rhs* in radians. | train | https://github.com/NiklasRosenstein/myo-python/blob/89a7480f8058061da7a3dd98ccec57a6b134ddf3/myo/math.py#L127-L132 | [
"def magnitude(self):\n \"\"\"\n Return the magnitude of this vector.\n \"\"\"\n\n return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)\n",
"def dot(self, rhs):\n \"\"\"\n Return the dot product of this vector and *rhs*.\n \"\"\"\n\n return self.x * rhs.x + self.y * rhs.y + self.z * rhs.z\n"
] | class Vector(object):
"""
A three-dimensional vector.
"""
__slots__ = ('x', 'y', 'z')
def __init__(self, x, y, z):
super(Vector, self).__init__()
self.x = float(x)
self.y = float(y)
self.z = float(z)
def __mul__(self, rhs):
"""
Multiplies the vector with *rhs* which can be either a scalar
to retrieve a new Vector or another vector to compute the dot
product.
"""
if isinstance(rhs, (six.integer_types, float)):
return Vector(self.x * rhs, self.y * rhs, self.z * rhs)
else:
return self.dot(rhs)
def __add__(self, rhs):
"""
Adds *self* to *rhs* and returns a new vector.
"""
if isinstance(rhs, (six.integer_types, float)):
return Vector(self.x + rhs, self.y + rhs, self.z + rhs)
else:
return Vector(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z)
def __sub__(self, rhs):
"""
Substracts *self* from *rhs* and returns a new vector.
"""
if isinstance(rhs, (six.integer_types, float)):
return Vector(self.x - rhs, self.y - rhs, self.z - rhs)
else:
return Vector(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z)
def __iter__(self):
return iter((self.x, self.y, self.z))
def __repr__(self):
return 'Vector({0}, {1}, {2})'.format(self.x, self.y, self.z)
def __invert__(self):
"""
Returns the inversion of the vector.
"""
return Vector(-self.x, -self.y, -self.z)
def __getitem__(self, index):
return (self.x, self.y, self.z)[index]
def copy(self):
"""
Returns a shallow copy of the vector.
"""
return Vector(self.x, self.y, self.z)
def magnitude(self):
"""
Return the magnitude of this vector.
"""
return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)
def normalized(self):
"""
Returns a normalized copy of this vector.
"""
norm = self.magnitude()
return Vector(self.x / norm, self.y / norm, self.z / norm)
def dot(self, rhs):
"""
Return the dot product of this vector and *rhs*.
"""
return self.x * rhs.x + self.y * rhs.y + self.z * rhs.z
def cross(self, rhs):
"""
Return the cross product of this vector and *rhs*.
"""
return Vector(
self.y * rhs.z - self.z * rhs.y,
self.z * rhs.x - self.x * rhs.z,
self.x * rhs.y - self.y * rhs.x)
__abs__ = magnitude
|
NiklasRosenstein/myo-python | myo/math.py | Quaternion.magnitude | python | def magnitude(self):
return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2 + self.w ** 2) | Returns the magnitude of the quaternion. | train | https://github.com/NiklasRosenstein/myo-python/blob/89a7480f8058061da7a3dd98ccec57a6b134ddf3/myo/math.py#L194-L199 | null | class Quaternion(object):
"""
This class represents a quaternion which can be used to represent
gimbal-lock free rotations.
This implementation can work with any vector type that has members
x, y and z and it has a constructor that accepts values for these
members in order. This is convenient when combining the Myo SDK
with other 3D APIs that provide a vector class.
"""
__slots__ = ('x', 'y', 'z', 'w')
def __init__(self, x, y, z, w):
super(Quaternion, self).__init__()
self.x = float(x)
self.y = float(y)
self.z = float(z)
self.w = float(w)
def __mul__(self, rhs):
"""
Multiplies *self* with the #Quaternion *rhs* and returns a new #Quaternion.
"""
if not isinstance(rhs, Quaternion):
raise TypeError('can only multiply with Quaternion')
return Quaternion(
self.w * rhs.x + self.x * rhs.w + self.y * rhs.z - self.z * rhs.y,
self.w * rhs.y - self.x * rhs.z + self.y * rhs.w + self.z * rhs.x,
self.w * rhs.z + self.x * rhs.y - self.y * rhs.x + self.z * rhs.w,
self.w * rhs.w - self.x * rhs.x - self.y * rhs.y - self.z * rhs.z)
def __iter__(self):
return iter((self.x, self.y, self.z, self.w))
def __repr__(self):
return '{}({0}, {1}, {2}, {3})'.format(
type(self).__name__, self.x, self.y, self.z, self.w)
def __invert__(self):
"""
Returns this Quaternion's conjugate.
"""
return Quaternion(-self.x, -self.y, -self.z, self.w)
def __getitem__(self, index):
return (self.x, self.y, self.z, self.w)[index]
def copy(self):
"""
Returns a shallow copy of the quaternion.
"""
return Quaternion(self.x, self.y, self.z, self.w)
def normalized(self):
"""
Returns the unit quaternion corresponding to the same rotation
as this one.
"""
magnitude = self.magnitude()
return Quaternion(
self.x / magnitude, self.y / magnitude,
self.z / magnitude, self.w / magnitude)
conjugate = __invert__
def rotate(self, vec):
"""
Returns *vec* rotated by this #Quaternion.
:param vec: A vector object.
:return: object of type of *vec*
"""
qvec = self * Quaternion(vec.x, vec.y, vec.z, 0) * ~self
return type(vec)(qvec.x, qvec.y, qvec.z)
# Reference:
# http://answers.unity3d.com/questions/416169/finding-pitchrollyaw-from-quaternions.html
@property
def roll(self):
""" Calculates the Roll of the Quaternion. """
x, y, z, w = self.x, self.y, self.z, self.w
return math.atan2(2*y*w - 2*x*z, 1 - 2*y*y - 2*z*z)
@property
def pitch(self):
""" Calculates the Pitch of the Quaternion. """
x, y, z, w = self.x, self.y, self.z, self.w
return math.atan2(2*x*w - 2*y*z, 1 - 2*x*x - 2*z*z)
@property
def yaw(self):
""" Calculates the Yaw of the Quaternion. """
x, y, z, w = self.x, self.y, self.z, self.w
return math.asin(2*x*y + 2*z*w)
@property
def rpy(self):
""" Calculates the Roll, Pitch and Yaw of the Quaternion. """
x, y, z, w = self.x, self.y, self.z, self.w
roll = math.atan2(2*y*w - 2*x*z, 1 - 2*y*y - 2*z*z)
pitch = math.atan2(2*x*w - 2*y*z, 1 - 2*x*x - 2*z*z)
yaw = math.asin(2*x*y + 2*z*w)
return (roll, pitch, yaw)
@staticmethod
def identity():
"""
Returns the identity #Quaternion.
"""
return Quaternion(0, 0, 0, 1)
@staticmethod
def rotation_of(source, dest):
"""
Returns a #Quaternion that represents a rotation from vector
*source* to *dest*.
"""
source = Vector(source.x, source.y, source.z)
dest = Vector(dest.x, dest.y, dest.z)
cross = source.cross(dest)
cos_theta = source.dot(dest)
# Return identity if the vectors are the same direction.
if cos_theta >= 1.0:
return Quaternion.identity()
# Product of the square of the magnitudes.
k = math.sqrt(source.dot(source), dest.dot(dest))
# Return identity in the degenerate case.
if k <= 0.0:
return Quaternion.identity()
# Special handling for vectors facing opposite directions.
if cos_theta / k <= -1:
x_axis = Vector(1, 0, 0)
y_axis = Vector(0, 1, 1)
if abs(source.dot(x_ais)) < 1.0:
cross = source.cross(x_axis)
else:
cross = source.cross(y_axis)
return Quaternion(cross.x, cross.y, cross.z, k + cos_theta)
@staticmethod
def from_axis_angle(axis, angle):
"""
Returns a #Quaternion that represents the right-handed
rotation of *angle* radians about the givne *axis*.
:param axis: The unit vector representing the axis of rotation.
:param angle: The angle of rotation, in radians.
"""
sincomp = math.sin(angle / 2.0)
return Quaternion(
axis.x * sincomp, axis.y * sincomp,
axis.z * sincomp, math.cos(angle / 2.0))
|
NiklasRosenstein/myo-python | myo/math.py | Quaternion.normalized | python | def normalized(self):
magnitude = self.magnitude()
return Quaternion(
self.x / magnitude, self.y / magnitude,
self.z / magnitude, self.w / magnitude) | Returns the unit quaternion corresponding to the same rotation
as this one. | train | https://github.com/NiklasRosenstein/myo-python/blob/89a7480f8058061da7a3dd98ccec57a6b134ddf3/myo/math.py#L201-L210 | [
"def magnitude(self):\n \"\"\"\n Returns the magnitude of the quaternion.\n \"\"\"\n\n return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2 + self.w ** 2)\n"
] | class Quaternion(object):
"""
This class represents a quaternion which can be used to represent
gimbal-lock free rotations.
This implementation can work with any vector type that has members
x, y and z and it has a constructor that accepts values for these
members in order. This is convenient when combining the Myo SDK
with other 3D APIs that provide a vector class.
"""
__slots__ = ('x', 'y', 'z', 'w')
def __init__(self, x, y, z, w):
super(Quaternion, self).__init__()
self.x = float(x)
self.y = float(y)
self.z = float(z)
self.w = float(w)
def __mul__(self, rhs):
"""
Multiplies *self* with the #Quaternion *rhs* and returns a new #Quaternion.
"""
if not isinstance(rhs, Quaternion):
raise TypeError('can only multiply with Quaternion')
return Quaternion(
self.w * rhs.x + self.x * rhs.w + self.y * rhs.z - self.z * rhs.y,
self.w * rhs.y - self.x * rhs.z + self.y * rhs.w + self.z * rhs.x,
self.w * rhs.z + self.x * rhs.y - self.y * rhs.x + self.z * rhs.w,
self.w * rhs.w - self.x * rhs.x - self.y * rhs.y - self.z * rhs.z)
def __iter__(self):
return iter((self.x, self.y, self.z, self.w))
def __repr__(self):
return '{}({0}, {1}, {2}, {3})'.format(
type(self).__name__, self.x, self.y, self.z, self.w)
def __invert__(self):
"""
Returns this Quaternion's conjugate.
"""
return Quaternion(-self.x, -self.y, -self.z, self.w)
def __getitem__(self, index):
return (self.x, self.y, self.z, self.w)[index]
def copy(self):
"""
Returns a shallow copy of the quaternion.
"""
return Quaternion(self.x, self.y, self.z, self.w)
def magnitude(self):
"""
Returns the magnitude of the quaternion.
"""
return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2 + self.w ** 2)
conjugate = __invert__
def rotate(self, vec):
"""
Returns *vec* rotated by this #Quaternion.
:param vec: A vector object.
:return: object of type of *vec*
"""
qvec = self * Quaternion(vec.x, vec.y, vec.z, 0) * ~self
return type(vec)(qvec.x, qvec.y, qvec.z)
# Reference:
# http://answers.unity3d.com/questions/416169/finding-pitchrollyaw-from-quaternions.html
@property
def roll(self):
""" Calculates the Roll of the Quaternion. """
x, y, z, w = self.x, self.y, self.z, self.w
return math.atan2(2*y*w - 2*x*z, 1 - 2*y*y - 2*z*z)
@property
def pitch(self):
""" Calculates the Pitch of the Quaternion. """
x, y, z, w = self.x, self.y, self.z, self.w
return math.atan2(2*x*w - 2*y*z, 1 - 2*x*x - 2*z*z)
@property
def yaw(self):
""" Calculates the Yaw of the Quaternion. """
x, y, z, w = self.x, self.y, self.z, self.w
return math.asin(2*x*y + 2*z*w)
@property
def rpy(self):
""" Calculates the Roll, Pitch and Yaw of the Quaternion. """
x, y, z, w = self.x, self.y, self.z, self.w
roll = math.atan2(2*y*w - 2*x*z, 1 - 2*y*y - 2*z*z)
pitch = math.atan2(2*x*w - 2*y*z, 1 - 2*x*x - 2*z*z)
yaw = math.asin(2*x*y + 2*z*w)
return (roll, pitch, yaw)
@staticmethod
def identity():
"""
Returns the identity #Quaternion.
"""
return Quaternion(0, 0, 0, 1)
@staticmethod
def rotation_of(source, dest):
"""
Returns a #Quaternion that represents a rotation from vector
*source* to *dest*.
"""
source = Vector(source.x, source.y, source.z)
dest = Vector(dest.x, dest.y, dest.z)
cross = source.cross(dest)
cos_theta = source.dot(dest)
# Return identity if the vectors are the same direction.
if cos_theta >= 1.0:
return Quaternion.identity()
# Product of the square of the magnitudes.
k = math.sqrt(source.dot(source), dest.dot(dest))
# Return identity in the degenerate case.
if k <= 0.0:
return Quaternion.identity()
# Special handling for vectors facing opposite directions.
if cos_theta / k <= -1:
x_axis = Vector(1, 0, 0)
y_axis = Vector(0, 1, 1)
if abs(source.dot(x_ais)) < 1.0:
cross = source.cross(x_axis)
else:
cross = source.cross(y_axis)
return Quaternion(cross.x, cross.y, cross.z, k + cos_theta)
@staticmethod
def from_axis_angle(axis, angle):
"""
Returns a #Quaternion that represents the right-handed
rotation of *angle* radians about the givne *axis*.
:param axis: The unit vector representing the axis of rotation.
:param angle: The angle of rotation, in radians.
"""
sincomp = math.sin(angle / 2.0)
return Quaternion(
axis.x * sincomp, axis.y * sincomp,
axis.z * sincomp, math.cos(angle / 2.0))
|
NiklasRosenstein/myo-python | myo/math.py | Quaternion.rotate | python | def rotate(self, vec):
qvec = self * Quaternion(vec.x, vec.y, vec.z, 0) * ~self
return type(vec)(qvec.x, qvec.y, qvec.z) | Returns *vec* rotated by this #Quaternion.
:param vec: A vector object.
:return: object of type of *vec* | train | https://github.com/NiklasRosenstein/myo-python/blob/89a7480f8058061da7a3dd98ccec57a6b134ddf3/myo/math.py#L214-L223 | null | class Quaternion(object):
"""
This class represents a quaternion which can be used to represent
gimbal-lock free rotations.
This implementation can work with any vector type that has members
x, y and z and it has a constructor that accepts values for these
members in order. This is convenient when combining the Myo SDK
with other 3D APIs that provide a vector class.
"""
__slots__ = ('x', 'y', 'z', 'w')
def __init__(self, x, y, z, w):
super(Quaternion, self).__init__()
self.x = float(x)
self.y = float(y)
self.z = float(z)
self.w = float(w)
def __mul__(self, rhs):
"""
Multiplies *self* with the #Quaternion *rhs* and returns a new #Quaternion.
"""
if not isinstance(rhs, Quaternion):
raise TypeError('can only multiply with Quaternion')
return Quaternion(
self.w * rhs.x + self.x * rhs.w + self.y * rhs.z - self.z * rhs.y,
self.w * rhs.y - self.x * rhs.z + self.y * rhs.w + self.z * rhs.x,
self.w * rhs.z + self.x * rhs.y - self.y * rhs.x + self.z * rhs.w,
self.w * rhs.w - self.x * rhs.x - self.y * rhs.y - self.z * rhs.z)
def __iter__(self):
return iter((self.x, self.y, self.z, self.w))
def __repr__(self):
return '{}({0}, {1}, {2}, {3})'.format(
type(self).__name__, self.x, self.y, self.z, self.w)
def __invert__(self):
"""
Returns this Quaternion's conjugate.
"""
return Quaternion(-self.x, -self.y, -self.z, self.w)
def __getitem__(self, index):
return (self.x, self.y, self.z, self.w)[index]
def copy(self):
"""
Returns a shallow copy of the quaternion.
"""
return Quaternion(self.x, self.y, self.z, self.w)
def magnitude(self):
"""
Returns the magnitude of the quaternion.
"""
return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2 + self.w ** 2)
def normalized(self):
"""
Returns the unit quaternion corresponding to the same rotation
as this one.
"""
magnitude = self.magnitude()
return Quaternion(
self.x / magnitude, self.y / magnitude,
self.z / magnitude, self.w / magnitude)
conjugate = __invert__
# Reference:
# http://answers.unity3d.com/questions/416169/finding-pitchrollyaw-from-quaternions.html
@property
def roll(self):
""" Calculates the Roll of the Quaternion. """
x, y, z, w = self.x, self.y, self.z, self.w
return math.atan2(2*y*w - 2*x*z, 1 - 2*y*y - 2*z*z)
@property
def pitch(self):
""" Calculates the Pitch of the Quaternion. """
x, y, z, w = self.x, self.y, self.z, self.w
return math.atan2(2*x*w - 2*y*z, 1 - 2*x*x - 2*z*z)
@property
def yaw(self):
""" Calculates the Yaw of the Quaternion. """
x, y, z, w = self.x, self.y, self.z, self.w
return math.asin(2*x*y + 2*z*w)
@property
def rpy(self):
""" Calculates the Roll, Pitch and Yaw of the Quaternion. """
x, y, z, w = self.x, self.y, self.z, self.w
roll = math.atan2(2*y*w - 2*x*z, 1 - 2*y*y - 2*z*z)
pitch = math.atan2(2*x*w - 2*y*z, 1 - 2*x*x - 2*z*z)
yaw = math.asin(2*x*y + 2*z*w)
return (roll, pitch, yaw)
@staticmethod
def identity():
"""
Returns the identity #Quaternion.
"""
return Quaternion(0, 0, 0, 1)
@staticmethod
def rotation_of(source, dest):
"""
Returns a #Quaternion that represents a rotation from vector
*source* to *dest*.
"""
source = Vector(source.x, source.y, source.z)
dest = Vector(dest.x, dest.y, dest.z)
cross = source.cross(dest)
cos_theta = source.dot(dest)
# Return identity if the vectors are the same direction.
if cos_theta >= 1.0:
return Quaternion.identity()
# Product of the square of the magnitudes.
k = math.sqrt(source.dot(source), dest.dot(dest))
# Return identity in the degenerate case.
if k <= 0.0:
return Quaternion.identity()
# Special handling for vectors facing opposite directions.
if cos_theta / k <= -1:
x_axis = Vector(1, 0, 0)
y_axis = Vector(0, 1, 1)
if abs(source.dot(x_ais)) < 1.0:
cross = source.cross(x_axis)
else:
cross = source.cross(y_axis)
return Quaternion(cross.x, cross.y, cross.z, k + cos_theta)
@staticmethod
def from_axis_angle(axis, angle):
"""
Returns a #Quaternion that represents the right-handed
rotation of *angle* radians about the givne *axis*.
:param axis: The unit vector representing the axis of rotation.
:param angle: The angle of rotation, in radians.
"""
sincomp = math.sin(angle / 2.0)
return Quaternion(
axis.x * sincomp, axis.y * sincomp,
axis.z * sincomp, math.cos(angle / 2.0))
|
NiklasRosenstein/myo-python | myo/math.py | Quaternion.roll | python | def roll(self):
x, y, z, w = self.x, self.y, self.z, self.w
return math.atan2(2*y*w - 2*x*z, 1 - 2*y*y - 2*z*z) | Calculates the Roll of the Quaternion. | train | https://github.com/NiklasRosenstein/myo-python/blob/89a7480f8058061da7a3dd98ccec57a6b134ddf3/myo/math.py#L229-L233 | null | class Quaternion(object):
"""
This class represents a quaternion which can be used to represent
gimbal-lock free rotations.
This implementation can work with any vector type that has members
x, y and z and it has a constructor that accepts values for these
members in order. This is convenient when combining the Myo SDK
with other 3D APIs that provide a vector class.
"""
__slots__ = ('x', 'y', 'z', 'w')
def __init__(self, x, y, z, w):
super(Quaternion, self).__init__()
self.x = float(x)
self.y = float(y)
self.z = float(z)
self.w = float(w)
def __mul__(self, rhs):
"""
Multiplies *self* with the #Quaternion *rhs* and returns a new #Quaternion.
"""
if not isinstance(rhs, Quaternion):
raise TypeError('can only multiply with Quaternion')
return Quaternion(
self.w * rhs.x + self.x * rhs.w + self.y * rhs.z - self.z * rhs.y,
self.w * rhs.y - self.x * rhs.z + self.y * rhs.w + self.z * rhs.x,
self.w * rhs.z + self.x * rhs.y - self.y * rhs.x + self.z * rhs.w,
self.w * rhs.w - self.x * rhs.x - self.y * rhs.y - self.z * rhs.z)
def __iter__(self):
return iter((self.x, self.y, self.z, self.w))
def __repr__(self):
return '{}({0}, {1}, {2}, {3})'.format(
type(self).__name__, self.x, self.y, self.z, self.w)
def __invert__(self):
"""
Returns this Quaternion's conjugate.
"""
return Quaternion(-self.x, -self.y, -self.z, self.w)
def __getitem__(self, index):
return (self.x, self.y, self.z, self.w)[index]
def copy(self):
"""
Returns a shallow copy of the quaternion.
"""
return Quaternion(self.x, self.y, self.z, self.w)
def magnitude(self):
"""
Returns the magnitude of the quaternion.
"""
return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2 + self.w ** 2)
def normalized(self):
"""
Returns the unit quaternion corresponding to the same rotation
as this one.
"""
magnitude = self.magnitude()
return Quaternion(
self.x / magnitude, self.y / magnitude,
self.z / magnitude, self.w / magnitude)
conjugate = __invert__
def rotate(self, vec):
"""
Returns *vec* rotated by this #Quaternion.
:param vec: A vector object.
:return: object of type of *vec*
"""
qvec = self * Quaternion(vec.x, vec.y, vec.z, 0) * ~self
return type(vec)(qvec.x, qvec.y, qvec.z)
# Reference:
# http://answers.unity3d.com/questions/416169/finding-pitchrollyaw-from-quaternions.html
@property
@property
def pitch(self):
""" Calculates the Pitch of the Quaternion. """
x, y, z, w = self.x, self.y, self.z, self.w
return math.atan2(2*x*w - 2*y*z, 1 - 2*x*x - 2*z*z)
@property
def yaw(self):
""" Calculates the Yaw of the Quaternion. """
x, y, z, w = self.x, self.y, self.z, self.w
return math.asin(2*x*y + 2*z*w)
@property
def rpy(self):
""" Calculates the Roll, Pitch and Yaw of the Quaternion. """
x, y, z, w = self.x, self.y, self.z, self.w
roll = math.atan2(2*y*w - 2*x*z, 1 - 2*y*y - 2*z*z)
pitch = math.atan2(2*x*w - 2*y*z, 1 - 2*x*x - 2*z*z)
yaw = math.asin(2*x*y + 2*z*w)
return (roll, pitch, yaw)
@staticmethod
def identity():
"""
Returns the identity #Quaternion.
"""
return Quaternion(0, 0, 0, 1)
@staticmethod
def rotation_of(source, dest):
"""
Returns a #Quaternion that represents a rotation from vector
*source* to *dest*.
"""
source = Vector(source.x, source.y, source.z)
dest = Vector(dest.x, dest.y, dest.z)
cross = source.cross(dest)
cos_theta = source.dot(dest)
# Return identity if the vectors are the same direction.
if cos_theta >= 1.0:
return Quaternion.identity()
# Product of the square of the magnitudes.
k = math.sqrt(source.dot(source), dest.dot(dest))
# Return identity in the degenerate case.
if k <= 0.0:
return Quaternion.identity()
# Special handling for vectors facing opposite directions.
if cos_theta / k <= -1:
x_axis = Vector(1, 0, 0)
y_axis = Vector(0, 1, 1)
if abs(source.dot(x_ais)) < 1.0:
cross = source.cross(x_axis)
else:
cross = source.cross(y_axis)
return Quaternion(cross.x, cross.y, cross.z, k + cos_theta)
@staticmethod
def from_axis_angle(axis, angle):
"""
Returns a #Quaternion that represents the right-handed
rotation of *angle* radians about the givne *axis*.
:param axis: The unit vector representing the axis of rotation.
:param angle: The angle of rotation, in radians.
"""
sincomp = math.sin(angle / 2.0)
return Quaternion(
axis.x * sincomp, axis.y * sincomp,
axis.z * sincomp, math.cos(angle / 2.0))
|
NiklasRosenstein/myo-python | myo/math.py | Quaternion.pitch | python | def pitch(self):
x, y, z, w = self.x, self.y, self.z, self.w
return math.atan2(2*x*w - 2*y*z, 1 - 2*x*x - 2*z*z) | Calculates the Pitch of the Quaternion. | train | https://github.com/NiklasRosenstein/myo-python/blob/89a7480f8058061da7a3dd98ccec57a6b134ddf3/myo/math.py#L236-L240 | null | class Quaternion(object):
"""
This class represents a quaternion which can be used to represent
gimbal-lock free rotations.
This implementation can work with any vector type that has members
x, y and z and it has a constructor that accepts values for these
members in order. This is convenient when combining the Myo SDK
with other 3D APIs that provide a vector class.
"""
__slots__ = ('x', 'y', 'z', 'w')
def __init__(self, x, y, z, w):
super(Quaternion, self).__init__()
self.x = float(x)
self.y = float(y)
self.z = float(z)
self.w = float(w)
def __mul__(self, rhs):
"""
Multiplies *self* with the #Quaternion *rhs* and returns a new #Quaternion.
"""
if not isinstance(rhs, Quaternion):
raise TypeError('can only multiply with Quaternion')
return Quaternion(
self.w * rhs.x + self.x * rhs.w + self.y * rhs.z - self.z * rhs.y,
self.w * rhs.y - self.x * rhs.z + self.y * rhs.w + self.z * rhs.x,
self.w * rhs.z + self.x * rhs.y - self.y * rhs.x + self.z * rhs.w,
self.w * rhs.w - self.x * rhs.x - self.y * rhs.y - self.z * rhs.z)
def __iter__(self):
return iter((self.x, self.y, self.z, self.w))
def __repr__(self):
return '{}({0}, {1}, {2}, {3})'.format(
type(self).__name__, self.x, self.y, self.z, self.w)
def __invert__(self):
"""
Returns this Quaternion's conjugate.
"""
return Quaternion(-self.x, -self.y, -self.z, self.w)
def __getitem__(self, index):
return (self.x, self.y, self.z, self.w)[index]
def copy(self):
"""
Returns a shallow copy of the quaternion.
"""
return Quaternion(self.x, self.y, self.z, self.w)
def magnitude(self):
"""
Returns the magnitude of the quaternion.
"""
return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2 + self.w ** 2)
def normalized(self):
"""
Returns the unit quaternion corresponding to the same rotation
as this one.
"""
magnitude = self.magnitude()
return Quaternion(
self.x / magnitude, self.y / magnitude,
self.z / magnitude, self.w / magnitude)
conjugate = __invert__
def rotate(self, vec):
"""
Returns *vec* rotated by this #Quaternion.
:param vec: A vector object.
:return: object of type of *vec*
"""
qvec = self * Quaternion(vec.x, vec.y, vec.z, 0) * ~self
return type(vec)(qvec.x, qvec.y, qvec.z)
# Reference:
# http://answers.unity3d.com/questions/416169/finding-pitchrollyaw-from-quaternions.html
@property
def roll(self):
""" Calculates the Roll of the Quaternion. """
x, y, z, w = self.x, self.y, self.z, self.w
return math.atan2(2*y*w - 2*x*z, 1 - 2*y*y - 2*z*z)
@property
@property
def yaw(self):
""" Calculates the Yaw of the Quaternion. """
x, y, z, w = self.x, self.y, self.z, self.w
return math.asin(2*x*y + 2*z*w)
@property
def rpy(self):
""" Calculates the Roll, Pitch and Yaw of the Quaternion. """
x, y, z, w = self.x, self.y, self.z, self.w
roll = math.atan2(2*y*w - 2*x*z, 1 - 2*y*y - 2*z*z)
pitch = math.atan2(2*x*w - 2*y*z, 1 - 2*x*x - 2*z*z)
yaw = math.asin(2*x*y + 2*z*w)
return (roll, pitch, yaw)
@staticmethod
def identity():
"""
Returns the identity #Quaternion.
"""
return Quaternion(0, 0, 0, 1)
@staticmethod
def rotation_of(source, dest):
"""
Returns a #Quaternion that represents a rotation from vector
*source* to *dest*.
"""
source = Vector(source.x, source.y, source.z)
dest = Vector(dest.x, dest.y, dest.z)
cross = source.cross(dest)
cos_theta = source.dot(dest)
# Return identity if the vectors are the same direction.
if cos_theta >= 1.0:
return Quaternion.identity()
# Product of the square of the magnitudes.
k = math.sqrt(source.dot(source), dest.dot(dest))
# Return identity in the degenerate case.
if k <= 0.0:
return Quaternion.identity()
# Special handling for vectors facing opposite directions.
if cos_theta / k <= -1:
x_axis = Vector(1, 0, 0)
y_axis = Vector(0, 1, 1)
if abs(source.dot(x_ais)) < 1.0:
cross = source.cross(x_axis)
else:
cross = source.cross(y_axis)
return Quaternion(cross.x, cross.y, cross.z, k + cos_theta)
@staticmethod
def from_axis_angle(axis, angle):
"""
Returns a #Quaternion that represents the right-handed
rotation of *angle* radians about the givne *axis*.
:param axis: The unit vector representing the axis of rotation.
:param angle: The angle of rotation, in radians.
"""
sincomp = math.sin(angle / 2.0)
return Quaternion(
axis.x * sincomp, axis.y * sincomp,
axis.z * sincomp, math.cos(angle / 2.0))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.