prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>math.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name
from __future__ import absolute_import
from math import acos, cos, pi, radians, sin, sqrt
import auttitude as at
import numpy as np
def normalized_cross(a, b):
"""
Returns the normalized cross product between vectors.
Uses numpy.cross().
Parameters:
a: First vector.
b: Second vector.
"""
c = np.cross(a, b)
length = sqrt(c.dot(c))
return c/length if length > 0 else c
def general_plane_intersection(n_a, da, n_b, db):
"""
Returns a point and direction vector for the line of intersection
of two planes in space, or None if planes are parallel.
Parameters:
n_a: Normal vector to plane A
da: Point of plane A
n_b: Normal vector to plane B
db: Point of plane B
"""
# https://en.wikipedia.org/wiki/Intersection_curve
n_a = np.array(n_a)
n_b = np.array(n_b)
da = np.array(da)
db = np.array(db)
l_v = np.cross(n_a, n_b)
norm_l = sqrt(np.dot(l_v, l_v))
if norm_l == 0:
return None
else:
l_v /= norm_l
aa = np.dot(n_a, n_a)
bb = np.dot(n_b, n_b)
ab = np.dot(n_a, n_b)
d_ = 1./(aa*bb - ab*ab)
l_0 = (da*bb - db*ab)*d_*n_a + (db*aa - da*ab)*d_*n_b
return l_v, l_0
def small_circle_intersection(axis_a, angle_a, axis_b, angle_b):
<|fim_middle|>
def build_rotation_matrix(azim, plng, rake):
"""
Returns the rotation matrix that rotates the North vector to the line given
by Azimuth and Plunge and East and Up vectors are rotate clock-wise by Rake
around the rotated North vector.
Parameters:
azim: Line Azimuth from North (degrees).
plng: Line Plunge measured from horizontal (degrees).
rake: Rotation angle around rotated axis (degrees).
"""
# pylint: disable=bad-whitespace
azim, plng, rake = radians(azim), radians(plng), radians(rake)
R1 = np.array((( cos(rake), 0., sin(rake)),
( 0., 1., 0. ),
(-sin(rake), 0., cos(rake))))
R2 = np.array((( 1., 0., 0. ),
( 0., cos(plng), sin(plng)),
( 0., -sin(plng), cos(plng))))
R3 = np.array((( cos(azim), sin(azim), 0. ),
(-sin(azim), cos(azim), 0. ),
( 0., 0., 1. )))
return R3.dot(R2).dot(R1)
def adjust_lines_to_planes(lines, planes):
"""
Project each given line to it's respective plane. Returns the projected
lines as a new LineSet and the angle (in radians) between each line and
plane prior to projection.
Parameters:
lines: A LineSet like object with an array of n Lines
planes: A PlaseSet like object with an array of n Planes
"""
lines = at.LineSet(lines)
planes = at.PlaneSet(planes)
angles = np.zeros(len(lines))
adjusted_lines = np.zeros_like(lines)
for i, (line, plane) in enumerate(zip(lines, planes)):
cos_theta = np.dot(line, plane)
angles[i] = pi/2. - acos(cos_theta)
adjusted_line = line - line*cos_theta
adjusted_lines[i] = adjusted_line/sqrt(np.dot(adjusted_line,
adjusted_line))
return adjusted_lines, angles
<|fim▁end|> | """
Finds the intersection between two small-circles returning zero, one or two
solutions as tuple.
Parameters:
axis_a: Vector defining first circle axis
angle_a: Small circle aperture angle (in radians) around axis_a
axis_b: Vector defining second circle axis
angle_b: Small circle aperture angle (in radians) around axis_b
"""
line = general_plane_intersection(axis_a, cos(angle_a),
axis_b, cos(angle_b))
if line is None:
return ()
l_v, l_0 = line
# https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection
b = 2*l_v.dot(l_0)
delta = b*b - 4*(l_0.dot(l_0) - 1)
# Should the answers be normalized?
if delta < 0:
return ()
elif delta == 0:
return -b/2.,
else:
sqrt_delta = sqrt(delta)
return l_0 + l_v*(-b - sqrt_delta)/2., l_0 + l_v*(-b + sqrt_delta)/2. |
<|file_name|>math.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name
from __future__ import absolute_import
from math import acos, cos, pi, radians, sin, sqrt
import auttitude as at
import numpy as np
def normalized_cross(a, b):
"""
Returns the normalized cross product between vectors.
Uses numpy.cross().
Parameters:
a: First vector.
b: Second vector.
"""
c = np.cross(a, b)
length = sqrt(c.dot(c))
return c/length if length > 0 else c
def general_plane_intersection(n_a, da, n_b, db):
"""
Returns a point and direction vector for the line of intersection
of two planes in space, or None if planes are parallel.
Parameters:
n_a: Normal vector to plane A
da: Point of plane A
n_b: Normal vector to plane B
db: Point of plane B
"""
# https://en.wikipedia.org/wiki/Intersection_curve
n_a = np.array(n_a)
n_b = np.array(n_b)
da = np.array(da)
db = np.array(db)
l_v = np.cross(n_a, n_b)
norm_l = sqrt(np.dot(l_v, l_v))
if norm_l == 0:
return None
else:
l_v /= norm_l
aa = np.dot(n_a, n_a)
bb = np.dot(n_b, n_b)
ab = np.dot(n_a, n_b)
d_ = 1./(aa*bb - ab*ab)
l_0 = (da*bb - db*ab)*d_*n_a + (db*aa - da*ab)*d_*n_b
return l_v, l_0
def small_circle_intersection(axis_a, angle_a, axis_b, angle_b):
"""
Finds the intersection between two small-circles returning zero, one or two
solutions as tuple.
Parameters:
axis_a: Vector defining first circle axis
angle_a: Small circle aperture angle (in radians) around axis_a
axis_b: Vector defining second circle axis
angle_b: Small circle aperture angle (in radians) around axis_b
"""
line = general_plane_intersection(axis_a, cos(angle_a),
axis_b, cos(angle_b))
if line is None:
return ()
l_v, l_0 = line
# https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection
b = 2*l_v.dot(l_0)
delta = b*b - 4*(l_0.dot(l_0) - 1)
# Should the answers be normalized?
if delta < 0:
return ()
elif delta == 0:
return -b/2.,
else:
sqrt_delta = sqrt(delta)
return l_0 + l_v*(-b - sqrt_delta)/2., l_0 + l_v*(-b + sqrt_delta)/2.
def build_rotation_matrix(azim, plng, rake):
<|fim_middle|>
def adjust_lines_to_planes(lines, planes):
"""
Project each given line to it's respective plane. Returns the projected
lines as a new LineSet and the angle (in radians) between each line and
plane prior to projection.
Parameters:
lines: A LineSet like object with an array of n Lines
planes: A PlaseSet like object with an array of n Planes
"""
lines = at.LineSet(lines)
planes = at.PlaneSet(planes)
angles = np.zeros(len(lines))
adjusted_lines = np.zeros_like(lines)
for i, (line, plane) in enumerate(zip(lines, planes)):
cos_theta = np.dot(line, plane)
angles[i] = pi/2. - acos(cos_theta)
adjusted_line = line - line*cos_theta
adjusted_lines[i] = adjusted_line/sqrt(np.dot(adjusted_line,
adjusted_line))
return adjusted_lines, angles
<|fim▁end|> | """
Returns the rotation matrix that rotates the North vector to the line given
by Azimuth and Plunge and East and Up vectors are rotate clock-wise by Rake
around the rotated North vector.
Parameters:
azim: Line Azimuth from North (degrees).
plng: Line Plunge measured from horizontal (degrees).
rake: Rotation angle around rotated axis (degrees).
"""
# pylint: disable=bad-whitespace
azim, plng, rake = radians(azim), radians(plng), radians(rake)
R1 = np.array((( cos(rake), 0., sin(rake)),
( 0., 1., 0. ),
(-sin(rake), 0., cos(rake))))
R2 = np.array((( 1., 0., 0. ),
( 0., cos(plng), sin(plng)),
( 0., -sin(plng), cos(plng))))
R3 = np.array((( cos(azim), sin(azim), 0. ),
(-sin(azim), cos(azim), 0. ),
( 0., 0., 1. )))
return R3.dot(R2).dot(R1) |
<|file_name|>math.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name
from __future__ import absolute_import
from math import acos, cos, pi, radians, sin, sqrt
import auttitude as at
import numpy as np
def normalized_cross(a, b):
"""
Returns the normalized cross product between vectors.
Uses numpy.cross().
Parameters:
a: First vector.
b: Second vector.
"""
c = np.cross(a, b)
length = sqrt(c.dot(c))
return c/length if length > 0 else c
def general_plane_intersection(n_a, da, n_b, db):
"""
Returns a point and direction vector for the line of intersection
of two planes in space, or None if planes are parallel.
Parameters:
n_a: Normal vector to plane A
da: Point of plane A
n_b: Normal vector to plane B
db: Point of plane B
"""
# https://en.wikipedia.org/wiki/Intersection_curve
n_a = np.array(n_a)
n_b = np.array(n_b)
da = np.array(da)
db = np.array(db)
l_v = np.cross(n_a, n_b)
norm_l = sqrt(np.dot(l_v, l_v))
if norm_l == 0:
return None
else:
l_v /= norm_l
aa = np.dot(n_a, n_a)
bb = np.dot(n_b, n_b)
ab = np.dot(n_a, n_b)
d_ = 1./(aa*bb - ab*ab)
l_0 = (da*bb - db*ab)*d_*n_a + (db*aa - da*ab)*d_*n_b
return l_v, l_0
def small_circle_intersection(axis_a, angle_a, axis_b, angle_b):
"""
Finds the intersection between two small-circles returning zero, one or two
solutions as tuple.
Parameters:
axis_a: Vector defining first circle axis
angle_a: Small circle aperture angle (in radians) around axis_a
axis_b: Vector defining second circle axis
angle_b: Small circle aperture angle (in radians) around axis_b
"""
line = general_plane_intersection(axis_a, cos(angle_a),
axis_b, cos(angle_b))
if line is None:
return ()
l_v, l_0 = line
# https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection
b = 2*l_v.dot(l_0)
delta = b*b - 4*(l_0.dot(l_0) - 1)
# Should the answers be normalized?
if delta < 0:
return ()
elif delta == 0:
return -b/2.,
else:
sqrt_delta = sqrt(delta)
return l_0 + l_v*(-b - sqrt_delta)/2., l_0 + l_v*(-b + sqrt_delta)/2.
def build_rotation_matrix(azim, plng, rake):
"""
Returns the rotation matrix that rotates the North vector to the line given
by Azimuth and Plunge and East and Up vectors are rotate clock-wise by Rake
around the rotated North vector.
Parameters:
azim: Line Azimuth from North (degrees).
plng: Line Plunge measured from horizontal (degrees).
rake: Rotation angle around rotated axis (degrees).
"""
# pylint: disable=bad-whitespace
azim, plng, rake = radians(azim), radians(plng), radians(rake)
R1 = np.array((( cos(rake), 0., sin(rake)),
( 0., 1., 0. ),
(-sin(rake), 0., cos(rake))))
R2 = np.array((( 1., 0., 0. ),
( 0., cos(plng), sin(plng)),
( 0., -sin(plng), cos(plng))))
R3 = np.array((( cos(azim), sin(azim), 0. ),
(-sin(azim), cos(azim), 0. ),
( 0., 0., 1. )))
return R3.dot(R2).dot(R1)
def adjust_lines_to_planes(lines, planes):
<|fim_middle|>
<|fim▁end|> | """
Project each given line to it's respective plane. Returns the projected
lines as a new LineSet and the angle (in radians) between each line and
plane prior to projection.
Parameters:
lines: A LineSet like object with an array of n Lines
planes: A PlaseSet like object with an array of n Planes
"""
lines = at.LineSet(lines)
planes = at.PlaneSet(planes)
angles = np.zeros(len(lines))
adjusted_lines = np.zeros_like(lines)
for i, (line, plane) in enumerate(zip(lines, planes)):
cos_theta = np.dot(line, plane)
angles[i] = pi/2. - acos(cos_theta)
adjusted_line = line - line*cos_theta
adjusted_lines[i] = adjusted_line/sqrt(np.dot(adjusted_line,
adjusted_line))
return adjusted_lines, angles |
<|file_name|>math.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name
from __future__ import absolute_import
from math import acos, cos, pi, radians, sin, sqrt
import auttitude as at
import numpy as np
def normalized_cross(a, b):
"""
Returns the normalized cross product between vectors.
Uses numpy.cross().
Parameters:
a: First vector.
b: Second vector.
"""
c = np.cross(a, b)
length = sqrt(c.dot(c))
return c/length if length > 0 else c
def general_plane_intersection(n_a, da, n_b, db):
"""
Returns a point and direction vector for the line of intersection
of two planes in space, or None if planes are parallel.
Parameters:
n_a: Normal vector to plane A
da: Point of plane A
n_b: Normal vector to plane B
db: Point of plane B
"""
# https://en.wikipedia.org/wiki/Intersection_curve
n_a = np.array(n_a)
n_b = np.array(n_b)
da = np.array(da)
db = np.array(db)
l_v = np.cross(n_a, n_b)
norm_l = sqrt(np.dot(l_v, l_v))
if norm_l == 0:
<|fim_middle|>
else:
l_v /= norm_l
aa = np.dot(n_a, n_a)
bb = np.dot(n_b, n_b)
ab = np.dot(n_a, n_b)
d_ = 1./(aa*bb - ab*ab)
l_0 = (da*bb - db*ab)*d_*n_a + (db*aa - da*ab)*d_*n_b
return l_v, l_0
def small_circle_intersection(axis_a, angle_a, axis_b, angle_b):
"""
Finds the intersection between two small-circles returning zero, one or two
solutions as tuple.
Parameters:
axis_a: Vector defining first circle axis
angle_a: Small circle aperture angle (in radians) around axis_a
axis_b: Vector defining second circle axis
angle_b: Small circle aperture angle (in radians) around axis_b
"""
line = general_plane_intersection(axis_a, cos(angle_a),
axis_b, cos(angle_b))
if line is None:
return ()
l_v, l_0 = line
# https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection
b = 2*l_v.dot(l_0)
delta = b*b - 4*(l_0.dot(l_0) - 1)
# Should the answers be normalized?
if delta < 0:
return ()
elif delta == 0:
return -b/2.,
else:
sqrt_delta = sqrt(delta)
return l_0 + l_v*(-b - sqrt_delta)/2., l_0 + l_v*(-b + sqrt_delta)/2.
def build_rotation_matrix(azim, plng, rake):
"""
Returns the rotation matrix that rotates the North vector to the line given
by Azimuth and Plunge and East and Up vectors are rotate clock-wise by Rake
around the rotated North vector.
Parameters:
azim: Line Azimuth from North (degrees).
plng: Line Plunge measured from horizontal (degrees).
rake: Rotation angle around rotated axis (degrees).
"""
# pylint: disable=bad-whitespace
azim, plng, rake = radians(azim), radians(plng), radians(rake)
R1 = np.array((( cos(rake), 0., sin(rake)),
( 0., 1., 0. ),
(-sin(rake), 0., cos(rake))))
R2 = np.array((( 1., 0., 0. ),
( 0., cos(plng), sin(plng)),
( 0., -sin(plng), cos(plng))))
R3 = np.array((( cos(azim), sin(azim), 0. ),
(-sin(azim), cos(azim), 0. ),
( 0., 0., 1. )))
return R3.dot(R2).dot(R1)
def adjust_lines_to_planes(lines, planes):
"""
Project each given line to it's respective plane. Returns the projected
lines as a new LineSet and the angle (in radians) between each line and
plane prior to projection.
Parameters:
lines: A LineSet like object with an array of n Lines
planes: A PlaseSet like object with an array of n Planes
"""
lines = at.LineSet(lines)
planes = at.PlaneSet(planes)
angles = np.zeros(len(lines))
adjusted_lines = np.zeros_like(lines)
for i, (line, plane) in enumerate(zip(lines, planes)):
cos_theta = np.dot(line, plane)
angles[i] = pi/2. - acos(cos_theta)
adjusted_line = line - line*cos_theta
adjusted_lines[i] = adjusted_line/sqrt(np.dot(adjusted_line,
adjusted_line))
return adjusted_lines, angles
<|fim▁end|> | return None |
<|file_name|>math.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name
from __future__ import absolute_import
from math import acos, cos, pi, radians, sin, sqrt
import auttitude as at
import numpy as np
def normalized_cross(a, b):
"""
Returns the normalized cross product between vectors.
Uses numpy.cross().
Parameters:
a: First vector.
b: Second vector.
"""
c = np.cross(a, b)
length = sqrt(c.dot(c))
return c/length if length > 0 else c
def general_plane_intersection(n_a, da, n_b, db):
"""
Returns a point and direction vector for the line of intersection
of two planes in space, or None if planes are parallel.
Parameters:
n_a: Normal vector to plane A
da: Point of plane A
n_b: Normal vector to plane B
db: Point of plane B
"""
# https://en.wikipedia.org/wiki/Intersection_curve
n_a = np.array(n_a)
n_b = np.array(n_b)
da = np.array(da)
db = np.array(db)
l_v = np.cross(n_a, n_b)
norm_l = sqrt(np.dot(l_v, l_v))
if norm_l == 0:
return None
else:
<|fim_middle|>
aa = np.dot(n_a, n_a)
bb = np.dot(n_b, n_b)
ab = np.dot(n_a, n_b)
d_ = 1./(aa*bb - ab*ab)
l_0 = (da*bb - db*ab)*d_*n_a + (db*aa - da*ab)*d_*n_b
return l_v, l_0
def small_circle_intersection(axis_a, angle_a, axis_b, angle_b):
"""
Finds the intersection between two small-circles returning zero, one or two
solutions as tuple.
Parameters:
axis_a: Vector defining first circle axis
angle_a: Small circle aperture angle (in radians) around axis_a
axis_b: Vector defining second circle axis
angle_b: Small circle aperture angle (in radians) around axis_b
"""
line = general_plane_intersection(axis_a, cos(angle_a),
axis_b, cos(angle_b))
if line is None:
return ()
l_v, l_0 = line
# https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection
b = 2*l_v.dot(l_0)
delta = b*b - 4*(l_0.dot(l_0) - 1)
# Should the answers be normalized?
if delta < 0:
return ()
elif delta == 0:
return -b/2.,
else:
sqrt_delta = sqrt(delta)
return l_0 + l_v*(-b - sqrt_delta)/2., l_0 + l_v*(-b + sqrt_delta)/2.
def build_rotation_matrix(azim, plng, rake):
"""
Returns the rotation matrix that rotates the North vector to the line given
by Azimuth and Plunge and East and Up vectors are rotate clock-wise by Rake
around the rotated North vector.
Parameters:
azim: Line Azimuth from North (degrees).
plng: Line Plunge measured from horizontal (degrees).
rake: Rotation angle around rotated axis (degrees).
"""
# pylint: disable=bad-whitespace
azim, plng, rake = radians(azim), radians(plng), radians(rake)
R1 = np.array((( cos(rake), 0., sin(rake)),
( 0., 1., 0. ),
(-sin(rake), 0., cos(rake))))
R2 = np.array((( 1., 0., 0. ),
( 0., cos(plng), sin(plng)),
( 0., -sin(plng), cos(plng))))
R3 = np.array((( cos(azim), sin(azim), 0. ),
(-sin(azim), cos(azim), 0. ),
( 0., 0., 1. )))
return R3.dot(R2).dot(R1)
def adjust_lines_to_planes(lines, planes):
"""
Project each given line to it's respective plane. Returns the projected
lines as a new LineSet and the angle (in radians) between each line and
plane prior to projection.
Parameters:
lines: A LineSet like object with an array of n Lines
planes: A PlaseSet like object with an array of n Planes
"""
lines = at.LineSet(lines)
planes = at.PlaneSet(planes)
angles = np.zeros(len(lines))
adjusted_lines = np.zeros_like(lines)
for i, (line, plane) in enumerate(zip(lines, planes)):
cos_theta = np.dot(line, plane)
angles[i] = pi/2. - acos(cos_theta)
adjusted_line = line - line*cos_theta
adjusted_lines[i] = adjusted_line/sqrt(np.dot(adjusted_line,
adjusted_line))
return adjusted_lines, angles
<|fim▁end|> | l_v /= norm_l |
<|file_name|>math.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name
from __future__ import absolute_import
from math import acos, cos, pi, radians, sin, sqrt
import auttitude as at
import numpy as np
def normalized_cross(a, b):
"""
Returns the normalized cross product between vectors.
Uses numpy.cross().
Parameters:
a: First vector.
b: Second vector.
"""
c = np.cross(a, b)
length = sqrt(c.dot(c))
return c/length if length > 0 else c
def general_plane_intersection(n_a, da, n_b, db):
"""
Returns a point and direction vector for the line of intersection
of two planes in space, or None if planes are parallel.
Parameters:
n_a: Normal vector to plane A
da: Point of plane A
n_b: Normal vector to plane B
db: Point of plane B
"""
# https://en.wikipedia.org/wiki/Intersection_curve
n_a = np.array(n_a)
n_b = np.array(n_b)
da = np.array(da)
db = np.array(db)
l_v = np.cross(n_a, n_b)
norm_l = sqrt(np.dot(l_v, l_v))
if norm_l == 0:
return None
else:
l_v /= norm_l
aa = np.dot(n_a, n_a)
bb = np.dot(n_b, n_b)
ab = np.dot(n_a, n_b)
d_ = 1./(aa*bb - ab*ab)
l_0 = (da*bb - db*ab)*d_*n_a + (db*aa - da*ab)*d_*n_b
return l_v, l_0
def small_circle_intersection(axis_a, angle_a, axis_b, angle_b):
"""
Finds the intersection between two small-circles returning zero, one or two
solutions as tuple.
Parameters:
axis_a: Vector defining first circle axis
angle_a: Small circle aperture angle (in radians) around axis_a
axis_b: Vector defining second circle axis
angle_b: Small circle aperture angle (in radians) around axis_b
"""
line = general_plane_intersection(axis_a, cos(angle_a),
axis_b, cos(angle_b))
if line is None:
<|fim_middle|>
l_v, l_0 = line
# https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection
b = 2*l_v.dot(l_0)
delta = b*b - 4*(l_0.dot(l_0) - 1)
# Should the answers be normalized?
if delta < 0:
return ()
elif delta == 0:
return -b/2.,
else:
sqrt_delta = sqrt(delta)
return l_0 + l_v*(-b - sqrt_delta)/2., l_0 + l_v*(-b + sqrt_delta)/2.
def build_rotation_matrix(azim, plng, rake):
"""
Returns the rotation matrix that rotates the North vector to the line given
by Azimuth and Plunge and East and Up vectors are rotate clock-wise by Rake
around the rotated North vector.
Parameters:
azim: Line Azimuth from North (degrees).
plng: Line Plunge measured from horizontal (degrees).
rake: Rotation angle around rotated axis (degrees).
"""
# pylint: disable=bad-whitespace
azim, plng, rake = radians(azim), radians(plng), radians(rake)
R1 = np.array((( cos(rake), 0., sin(rake)),
( 0., 1., 0. ),
(-sin(rake), 0., cos(rake))))
R2 = np.array((( 1., 0., 0. ),
( 0., cos(plng), sin(plng)),
( 0., -sin(plng), cos(plng))))
R3 = np.array((( cos(azim), sin(azim), 0. ),
(-sin(azim), cos(azim), 0. ),
( 0., 0., 1. )))
return R3.dot(R2).dot(R1)
def adjust_lines_to_planes(lines, planes):
"""
Project each given line to it's respective plane. Returns the projected
lines as a new LineSet and the angle (in radians) between each line and
plane prior to projection.
Parameters:
lines: A LineSet like object with an array of n Lines
planes: A PlaseSet like object with an array of n Planes
"""
lines = at.LineSet(lines)
planes = at.PlaneSet(planes)
angles = np.zeros(len(lines))
adjusted_lines = np.zeros_like(lines)
for i, (line, plane) in enumerate(zip(lines, planes)):
cos_theta = np.dot(line, plane)
angles[i] = pi/2. - acos(cos_theta)
adjusted_line = line - line*cos_theta
adjusted_lines[i] = adjusted_line/sqrt(np.dot(adjusted_line,
adjusted_line))
return adjusted_lines, angles
<|fim▁end|> | return () |
<|file_name|>math.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name
from __future__ import absolute_import
from math import acos, cos, pi, radians, sin, sqrt
import auttitude as at
import numpy as np
def normalized_cross(a, b):
"""
Returns the normalized cross product between vectors.
Uses numpy.cross().
Parameters:
a: First vector.
b: Second vector.
"""
c = np.cross(a, b)
length = sqrt(c.dot(c))
return c/length if length > 0 else c
def general_plane_intersection(n_a, da, n_b, db):
"""
Returns a point and direction vector for the line of intersection
of two planes in space, or None if planes are parallel.
Parameters:
n_a: Normal vector to plane A
da: Point of plane A
n_b: Normal vector to plane B
db: Point of plane B
"""
# https://en.wikipedia.org/wiki/Intersection_curve
n_a = np.array(n_a)
n_b = np.array(n_b)
da = np.array(da)
db = np.array(db)
l_v = np.cross(n_a, n_b)
norm_l = sqrt(np.dot(l_v, l_v))
if norm_l == 0:
return None
else:
l_v /= norm_l
aa = np.dot(n_a, n_a)
bb = np.dot(n_b, n_b)
ab = np.dot(n_a, n_b)
d_ = 1./(aa*bb - ab*ab)
l_0 = (da*bb - db*ab)*d_*n_a + (db*aa - da*ab)*d_*n_b
return l_v, l_0
def small_circle_intersection(axis_a, angle_a, axis_b, angle_b):
"""
Finds the intersection between two small-circles returning zero, one or two
solutions as tuple.
Parameters:
axis_a: Vector defining first circle axis
angle_a: Small circle aperture angle (in radians) around axis_a
axis_b: Vector defining second circle axis
angle_b: Small circle aperture angle (in radians) around axis_b
"""
line = general_plane_intersection(axis_a, cos(angle_a),
axis_b, cos(angle_b))
if line is None:
return ()
l_v, l_0 = line
# https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection
b = 2*l_v.dot(l_0)
delta = b*b - 4*(l_0.dot(l_0) - 1)
# Should the answers be normalized?
if delta < 0:
<|fim_middle|>
elif delta == 0:
return -b/2.,
else:
sqrt_delta = sqrt(delta)
return l_0 + l_v*(-b - sqrt_delta)/2., l_0 + l_v*(-b + sqrt_delta)/2.
def build_rotation_matrix(azim, plng, rake):
"""
Returns the rotation matrix that rotates the North vector to the line given
by Azimuth and Plunge and East and Up vectors are rotate clock-wise by Rake
around the rotated North vector.
Parameters:
azim: Line Azimuth from North (degrees).
plng: Line Plunge measured from horizontal (degrees).
rake: Rotation angle around rotated axis (degrees).
"""
# pylint: disable=bad-whitespace
azim, plng, rake = radians(azim), radians(plng), radians(rake)
R1 = np.array((( cos(rake), 0., sin(rake)),
( 0., 1., 0. ),
(-sin(rake), 0., cos(rake))))
R2 = np.array((( 1., 0., 0. ),
( 0., cos(plng), sin(plng)),
( 0., -sin(plng), cos(plng))))
R3 = np.array((( cos(azim), sin(azim), 0. ),
(-sin(azim), cos(azim), 0. ),
( 0., 0., 1. )))
return R3.dot(R2).dot(R1)
def adjust_lines_to_planes(lines, planes):
"""
Project each given line to it's respective plane. Returns the projected
lines as a new LineSet and the angle (in radians) between each line and
plane prior to projection.
Parameters:
lines: A LineSet like object with an array of n Lines
planes: A PlaseSet like object with an array of n Planes
"""
lines = at.LineSet(lines)
planes = at.PlaneSet(planes)
angles = np.zeros(len(lines))
adjusted_lines = np.zeros_like(lines)
for i, (line, plane) in enumerate(zip(lines, planes)):
cos_theta = np.dot(line, plane)
angles[i] = pi/2. - acos(cos_theta)
adjusted_line = line - line*cos_theta
adjusted_lines[i] = adjusted_line/sqrt(np.dot(adjusted_line,
adjusted_line))
return adjusted_lines, angles
<|fim▁end|> | return () |
<|file_name|>math.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name
from __future__ import absolute_import
from math import acos, cos, pi, radians, sin, sqrt
import auttitude as at
import numpy as np
def normalized_cross(a, b):
"""
Returns the normalized cross product between vectors.
Uses numpy.cross().
Parameters:
a: First vector.
b: Second vector.
"""
c = np.cross(a, b)
length = sqrt(c.dot(c))
return c/length if length > 0 else c
def general_plane_intersection(n_a, da, n_b, db):
"""
Returns a point and direction vector for the line of intersection
of two planes in space, or None if planes are parallel.
Parameters:
n_a: Normal vector to plane A
da: Point of plane A
n_b: Normal vector to plane B
db: Point of plane B
"""
# https://en.wikipedia.org/wiki/Intersection_curve
n_a = np.array(n_a)
n_b = np.array(n_b)
da = np.array(da)
db = np.array(db)
l_v = np.cross(n_a, n_b)
norm_l = sqrt(np.dot(l_v, l_v))
if norm_l == 0:
return None
else:
l_v /= norm_l
aa = np.dot(n_a, n_a)
bb = np.dot(n_b, n_b)
ab = np.dot(n_a, n_b)
d_ = 1./(aa*bb - ab*ab)
l_0 = (da*bb - db*ab)*d_*n_a + (db*aa - da*ab)*d_*n_b
return l_v, l_0
def small_circle_intersection(axis_a, angle_a, axis_b, angle_b):
"""
Finds the intersection between two small-circles returning zero, one or two
solutions as tuple.
Parameters:
axis_a: Vector defining first circle axis
angle_a: Small circle aperture angle (in radians) around axis_a
axis_b: Vector defining second circle axis
angle_b: Small circle aperture angle (in radians) around axis_b
"""
line = general_plane_intersection(axis_a, cos(angle_a),
axis_b, cos(angle_b))
if line is None:
return ()
l_v, l_0 = line
# https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection
b = 2*l_v.dot(l_0)
delta = b*b - 4*(l_0.dot(l_0) - 1)
# Should the answers be normalized?
if delta < 0:
return ()
elif delta == 0:
<|fim_middle|>
else:
sqrt_delta = sqrt(delta)
return l_0 + l_v*(-b - sqrt_delta)/2., l_0 + l_v*(-b + sqrt_delta)/2.
def build_rotation_matrix(azim, plng, rake):
"""
Returns the rotation matrix that rotates the North vector to the line given
by Azimuth and Plunge and East and Up vectors are rotate clock-wise by Rake
around the rotated North vector.
Parameters:
azim: Line Azimuth from North (degrees).
plng: Line Plunge measured from horizontal (degrees).
rake: Rotation angle around rotated axis (degrees).
"""
# pylint: disable=bad-whitespace
azim, plng, rake = radians(azim), radians(plng), radians(rake)
R1 = np.array((( cos(rake), 0., sin(rake)),
( 0., 1., 0. ),
(-sin(rake), 0., cos(rake))))
R2 = np.array((( 1., 0., 0. ),
( 0., cos(plng), sin(plng)),
( 0., -sin(plng), cos(plng))))
R3 = np.array((( cos(azim), sin(azim), 0. ),
(-sin(azim), cos(azim), 0. ),
( 0., 0., 1. )))
return R3.dot(R2).dot(R1)
def adjust_lines_to_planes(lines, planes):
"""
Project each given line to it's respective plane. Returns the projected
lines as a new LineSet and the angle (in radians) between each line and
plane prior to projection.
Parameters:
lines: A LineSet like object with an array of n Lines
planes: A PlaseSet like object with an array of n Planes
"""
lines = at.LineSet(lines)
planes = at.PlaneSet(planes)
angles = np.zeros(len(lines))
adjusted_lines = np.zeros_like(lines)
for i, (line, plane) in enumerate(zip(lines, planes)):
cos_theta = np.dot(line, plane)
angles[i] = pi/2. - acos(cos_theta)
adjusted_line = line - line*cos_theta
adjusted_lines[i] = adjusted_line/sqrt(np.dot(adjusted_line,
adjusted_line))
return adjusted_lines, angles
<|fim▁end|> | return -b/2., |
<|file_name|>math.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name
from __future__ import absolute_import
from math import acos, cos, pi, radians, sin, sqrt
import auttitude as at
import numpy as np
def normalized_cross(a, b):
"""
Returns the normalized cross product between vectors.
Uses numpy.cross().
Parameters:
a: First vector.
b: Second vector.
"""
c = np.cross(a, b)
length = sqrt(c.dot(c))
return c/length if length > 0 else c
def general_plane_intersection(n_a, da, n_b, db):
"""
Returns a point and direction vector for the line of intersection
of two planes in space, or None if planes are parallel.
Parameters:
n_a: Normal vector to plane A
da: Point of plane A
n_b: Normal vector to plane B
db: Point of plane B
"""
# https://en.wikipedia.org/wiki/Intersection_curve
n_a = np.array(n_a)
n_b = np.array(n_b)
da = np.array(da)
db = np.array(db)
l_v = np.cross(n_a, n_b)
norm_l = sqrt(np.dot(l_v, l_v))
if norm_l == 0:
return None
else:
l_v /= norm_l
aa = np.dot(n_a, n_a)
bb = np.dot(n_b, n_b)
ab = np.dot(n_a, n_b)
d_ = 1./(aa*bb - ab*ab)
l_0 = (da*bb - db*ab)*d_*n_a + (db*aa - da*ab)*d_*n_b
return l_v, l_0
def small_circle_intersection(axis_a, angle_a, axis_b, angle_b):
"""
Finds the intersection between two small-circles returning zero, one or two
solutions as tuple.
Parameters:
axis_a: Vector defining first circle axis
angle_a: Small circle aperture angle (in radians) around axis_a
axis_b: Vector defining second circle axis
angle_b: Small circle aperture angle (in radians) around axis_b
"""
line = general_plane_intersection(axis_a, cos(angle_a),
axis_b, cos(angle_b))
if line is None:
return ()
l_v, l_0 = line
# https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection
b = 2*l_v.dot(l_0)
delta = b*b - 4*(l_0.dot(l_0) - 1)
# Should the answers be normalized?
if delta < 0:
return ()
elif delta == 0:
return -b/2.,
else:
<|fim_middle|>
def build_rotation_matrix(azim, plng, rake):
"""
Returns the rotation matrix that rotates the North vector to the line given
by Azimuth and Plunge and East and Up vectors are rotate clock-wise by Rake
around the rotated North vector.
Parameters:
azim: Line Azimuth from North (degrees).
plng: Line Plunge measured from horizontal (degrees).
rake: Rotation angle around rotated axis (degrees).
"""
# pylint: disable=bad-whitespace
azim, plng, rake = radians(azim), radians(plng), radians(rake)
R1 = np.array((( cos(rake), 0., sin(rake)),
( 0., 1., 0. ),
(-sin(rake), 0., cos(rake))))
R2 = np.array((( 1., 0., 0. ),
( 0., cos(plng), sin(plng)),
( 0., -sin(plng), cos(plng))))
R3 = np.array((( cos(azim), sin(azim), 0. ),
(-sin(azim), cos(azim), 0. ),
( 0., 0., 1. )))
return R3.dot(R2).dot(R1)
def adjust_lines_to_planes(lines, planes):
"""
Project each given line to it's respective plane. Returns the projected
lines as a new LineSet and the angle (in radians) between each line and
plane prior to projection.
Parameters:
lines: A LineSet like object with an array of n Lines
planes: A PlaseSet like object with an array of n Planes
"""
lines = at.LineSet(lines)
planes = at.PlaneSet(planes)
angles = np.zeros(len(lines))
adjusted_lines = np.zeros_like(lines)
for i, (line, plane) in enumerate(zip(lines, planes)):
cos_theta = np.dot(line, plane)
angles[i] = pi/2. - acos(cos_theta)
adjusted_line = line - line*cos_theta
adjusted_lines[i] = adjusted_line/sqrt(np.dot(adjusted_line,
adjusted_line))
return adjusted_lines, angles
<|fim▁end|> | sqrt_delta = sqrt(delta)
return l_0 + l_v*(-b - sqrt_delta)/2., l_0 + l_v*(-b + sqrt_delta)/2. |
<|file_name|>math.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name
from __future__ import absolute_import
from math import acos, cos, pi, radians, sin, sqrt
import auttitude as at
import numpy as np
def <|fim_middle|>(a, b):
"""
Returns the normalized cross product between vectors.
Uses numpy.cross().
Parameters:
a: First vector.
b: Second vector.
"""
c = np.cross(a, b)
length = sqrt(c.dot(c))
return c/length if length > 0 else c
def general_plane_intersection(n_a, da, n_b, db):
"""
Returns a point and direction vector for the line of intersection
of two planes in space, or None if planes are parallel.
Parameters:
n_a: Normal vector to plane A
da: Point of plane A
n_b: Normal vector to plane B
db: Point of plane B
"""
# https://en.wikipedia.org/wiki/Intersection_curve
n_a = np.array(n_a)
n_b = np.array(n_b)
da = np.array(da)
db = np.array(db)
l_v = np.cross(n_a, n_b)
norm_l = sqrt(np.dot(l_v, l_v))
if norm_l == 0:
return None
else:
l_v /= norm_l
aa = np.dot(n_a, n_a)
bb = np.dot(n_b, n_b)
ab = np.dot(n_a, n_b)
d_ = 1./(aa*bb - ab*ab)
l_0 = (da*bb - db*ab)*d_*n_a + (db*aa - da*ab)*d_*n_b
return l_v, l_0
def small_circle_intersection(axis_a, angle_a, axis_b, angle_b):
"""
Finds the intersection between two small-circles returning zero, one or two
solutions as tuple.
Parameters:
axis_a: Vector defining first circle axis
angle_a: Small circle aperture angle (in radians) around axis_a
axis_b: Vector defining second circle axis
angle_b: Small circle aperture angle (in radians) around axis_b
"""
line = general_plane_intersection(axis_a, cos(angle_a),
axis_b, cos(angle_b))
if line is None:
return ()
l_v, l_0 = line
# https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection
b = 2*l_v.dot(l_0)
delta = b*b - 4*(l_0.dot(l_0) - 1)
# Should the answers be normalized?
if delta < 0:
return ()
elif delta == 0:
return -b/2.,
else:
sqrt_delta = sqrt(delta)
return l_0 + l_v*(-b - sqrt_delta)/2., l_0 + l_v*(-b + sqrt_delta)/2.
def build_rotation_matrix(azim, plng, rake):
"""
Returns the rotation matrix that rotates the North vector to the line given
by Azimuth and Plunge and East and Up vectors are rotate clock-wise by Rake
around the rotated North vector.
Parameters:
azim: Line Azimuth from North (degrees).
plng: Line Plunge measured from horizontal (degrees).
rake: Rotation angle around rotated axis (degrees).
"""
# pylint: disable=bad-whitespace
azim, plng, rake = radians(azim), radians(plng), radians(rake)
R1 = np.array((( cos(rake), 0., sin(rake)),
( 0., 1., 0. ),
(-sin(rake), 0., cos(rake))))
R2 = np.array((( 1., 0., 0. ),
( 0., cos(plng), sin(plng)),
( 0., -sin(plng), cos(plng))))
R3 = np.array((( cos(azim), sin(azim), 0. ),
(-sin(azim), cos(azim), 0. ),
( 0., 0., 1. )))
return R3.dot(R2).dot(R1)
def adjust_lines_to_planes(lines, planes):
"""
Project each given line to it's respective plane. Returns the projected
lines as a new LineSet and the angle (in radians) between each line and
plane prior to projection.
Parameters:
lines: A LineSet like object with an array of n Lines
planes: A PlaseSet like object with an array of n Planes
"""
lines = at.LineSet(lines)
planes = at.PlaneSet(planes)
angles = np.zeros(len(lines))
adjusted_lines = np.zeros_like(lines)
for i, (line, plane) in enumerate(zip(lines, planes)):
cos_theta = np.dot(line, plane)
angles[i] = pi/2. - acos(cos_theta)
adjusted_line = line - line*cos_theta
adjusted_lines[i] = adjusted_line/sqrt(np.dot(adjusted_line,
adjusted_line))
return adjusted_lines, angles
<|fim▁end|> | normalized_cross |
<|file_name|>math.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name
from __future__ import absolute_import
from math import acos, cos, pi, radians, sin, sqrt
import auttitude as at
import numpy as np
def normalized_cross(a, b):
"""
Returns the normalized cross product between vectors.
Uses numpy.cross().
Parameters:
a: First vector.
b: Second vector.
"""
c = np.cross(a, b)
length = sqrt(c.dot(c))
return c/length if length > 0 else c
def <|fim_middle|>(n_a, da, n_b, db):
"""
Returns a point and direction vector for the line of intersection
of two planes in space, or None if planes are parallel.
Parameters:
n_a: Normal vector to plane A
da: Point of plane A
n_b: Normal vector to plane B
db: Point of plane B
"""
# https://en.wikipedia.org/wiki/Intersection_curve
n_a = np.array(n_a)
n_b = np.array(n_b)
da = np.array(da)
db = np.array(db)
l_v = np.cross(n_a, n_b)
norm_l = sqrt(np.dot(l_v, l_v))
if norm_l == 0:
return None
else:
l_v /= norm_l
aa = np.dot(n_a, n_a)
bb = np.dot(n_b, n_b)
ab = np.dot(n_a, n_b)
d_ = 1./(aa*bb - ab*ab)
l_0 = (da*bb - db*ab)*d_*n_a + (db*aa - da*ab)*d_*n_b
return l_v, l_0
def small_circle_intersection(axis_a, angle_a, axis_b, angle_b):
"""
Finds the intersection between two small-circles returning zero, one or two
solutions as tuple.
Parameters:
axis_a: Vector defining first circle axis
angle_a: Small circle aperture angle (in radians) around axis_a
axis_b: Vector defining second circle axis
angle_b: Small circle aperture angle (in radians) around axis_b
"""
line = general_plane_intersection(axis_a, cos(angle_a),
axis_b, cos(angle_b))
if line is None:
return ()
l_v, l_0 = line
# https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection
b = 2*l_v.dot(l_0)
delta = b*b - 4*(l_0.dot(l_0) - 1)
# Should the answers be normalized?
if delta < 0:
return ()
elif delta == 0:
return -b/2.,
else:
sqrt_delta = sqrt(delta)
return l_0 + l_v*(-b - sqrt_delta)/2., l_0 + l_v*(-b + sqrt_delta)/2.
def build_rotation_matrix(azim, plng, rake):
"""
Returns the rotation matrix that rotates the North vector to the line given
by Azimuth and Plunge and East and Up vectors are rotate clock-wise by Rake
around the rotated North vector.
Parameters:
azim: Line Azimuth from North (degrees).
plng: Line Plunge measured from horizontal (degrees).
rake: Rotation angle around rotated axis (degrees).
"""
# pylint: disable=bad-whitespace
azim, plng, rake = radians(azim), radians(plng), radians(rake)
R1 = np.array((( cos(rake), 0., sin(rake)),
( 0., 1., 0. ),
(-sin(rake), 0., cos(rake))))
R2 = np.array((( 1., 0., 0. ),
( 0., cos(plng), sin(plng)),
( 0., -sin(plng), cos(plng))))
R3 = np.array((( cos(azim), sin(azim), 0. ),
(-sin(azim), cos(azim), 0. ),
( 0., 0., 1. )))
return R3.dot(R2).dot(R1)
def adjust_lines_to_planes(lines, planes):
"""
Project each given line to it's respective plane. Returns the projected
lines as a new LineSet and the angle (in radians) between each line and
plane prior to projection.
Parameters:
lines: A LineSet like object with an array of n Lines
planes: A PlaseSet like object with an array of n Planes
"""
lines = at.LineSet(lines)
planes = at.PlaneSet(planes)
angles = np.zeros(len(lines))
adjusted_lines = np.zeros_like(lines)
for i, (line, plane) in enumerate(zip(lines, planes)):
cos_theta = np.dot(line, plane)
angles[i] = pi/2. - acos(cos_theta)
adjusted_line = line - line*cos_theta
adjusted_lines[i] = adjusted_line/sqrt(np.dot(adjusted_line,
adjusted_line))
return adjusted_lines, angles
<|fim▁end|> | general_plane_intersection |
<|file_name|>math.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name
from __future__ import absolute_import
from math import acos, cos, pi, radians, sin, sqrt
import auttitude as at
import numpy as np
def normalized_cross(a, b):
"""
Returns the normalized cross product between vectors.
Uses numpy.cross().
Parameters:
a: First vector.
b: Second vector.
"""
c = np.cross(a, b)
length = sqrt(c.dot(c))
return c/length if length > 0 else c
def general_plane_intersection(n_a, da, n_b, db):
"""
Returns a point and direction vector for the line of intersection
of two planes in space, or None if planes are parallel.
Parameters:
n_a: Normal vector to plane A
da: Point of plane A
n_b: Normal vector to plane B
db: Point of plane B
"""
# https://en.wikipedia.org/wiki/Intersection_curve
n_a = np.array(n_a)
n_b = np.array(n_b)
da = np.array(da)
db = np.array(db)
l_v = np.cross(n_a, n_b)
norm_l = sqrt(np.dot(l_v, l_v))
if norm_l == 0:
return None
else:
l_v /= norm_l
aa = np.dot(n_a, n_a)
bb = np.dot(n_b, n_b)
ab = np.dot(n_a, n_b)
d_ = 1./(aa*bb - ab*ab)
l_0 = (da*bb - db*ab)*d_*n_a + (db*aa - da*ab)*d_*n_b
return l_v, l_0
def <|fim_middle|>(axis_a, angle_a, axis_b, angle_b):
"""
Finds the intersection between two small-circles returning zero, one or two
solutions as tuple.
Parameters:
axis_a: Vector defining first circle axis
angle_a: Small circle aperture angle (in radians) around axis_a
axis_b: Vector defining second circle axis
angle_b: Small circle aperture angle (in radians) around axis_b
"""
line = general_plane_intersection(axis_a, cos(angle_a),
axis_b, cos(angle_b))
if line is None:
return ()
l_v, l_0 = line
# https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection
b = 2*l_v.dot(l_0)
delta = b*b - 4*(l_0.dot(l_0) - 1)
# Should the answers be normalized?
if delta < 0:
return ()
elif delta == 0:
return -b/2.,
else:
sqrt_delta = sqrt(delta)
return l_0 + l_v*(-b - sqrt_delta)/2., l_0 + l_v*(-b + sqrt_delta)/2.
def build_rotation_matrix(azim, plng, rake):
"""
Returns the rotation matrix that rotates the North vector to the line given
by Azimuth and Plunge and East and Up vectors are rotate clock-wise by Rake
around the rotated North vector.
Parameters:
azim: Line Azimuth from North (degrees).
plng: Line Plunge measured from horizontal (degrees).
rake: Rotation angle around rotated axis (degrees).
"""
# pylint: disable=bad-whitespace
azim, plng, rake = radians(azim), radians(plng), radians(rake)
R1 = np.array((( cos(rake), 0., sin(rake)),
( 0., 1., 0. ),
(-sin(rake), 0., cos(rake))))
R2 = np.array((( 1., 0., 0. ),
( 0., cos(plng), sin(plng)),
( 0., -sin(plng), cos(plng))))
R3 = np.array((( cos(azim), sin(azim), 0. ),
(-sin(azim), cos(azim), 0. ),
( 0., 0., 1. )))
return R3.dot(R2).dot(R1)
def adjust_lines_to_planes(lines, planes):
"""
Project each given line to it's respective plane. Returns the projected
lines as a new LineSet and the angle (in radians) between each line and
plane prior to projection.
Parameters:
lines: A LineSet like object with an array of n Lines
planes: A PlaseSet like object with an array of n Planes
"""
lines = at.LineSet(lines)
planes = at.PlaneSet(planes)
angles = np.zeros(len(lines))
adjusted_lines = np.zeros_like(lines)
for i, (line, plane) in enumerate(zip(lines, planes)):
cos_theta = np.dot(line, plane)
angles[i] = pi/2. - acos(cos_theta)
adjusted_line = line - line*cos_theta
adjusted_lines[i] = adjusted_line/sqrt(np.dot(adjusted_line,
adjusted_line))
return adjusted_lines, angles
<|fim▁end|> | small_circle_intersection |
<|file_name|>math.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name
from __future__ import absolute_import
from math import acos, cos, pi, radians, sin, sqrt
import auttitude as at
import numpy as np
def normalized_cross(a, b):
"""
Returns the normalized cross product between vectors.
Uses numpy.cross().
Parameters:
a: First vector.
b: Second vector.
"""
c = np.cross(a, b)
length = sqrt(c.dot(c))
return c/length if length > 0 else c
def general_plane_intersection(n_a, da, n_b, db):
"""
Returns a point and direction vector for the line of intersection
of two planes in space, or None if planes are parallel.
Parameters:
n_a: Normal vector to plane A
da: Point of plane A
n_b: Normal vector to plane B
db: Point of plane B
"""
# https://en.wikipedia.org/wiki/Intersection_curve
n_a = np.array(n_a)
n_b = np.array(n_b)
da = np.array(da)
db = np.array(db)
l_v = np.cross(n_a, n_b)
norm_l = sqrt(np.dot(l_v, l_v))
if norm_l == 0:
return None
else:
l_v /= norm_l
aa = np.dot(n_a, n_a)
bb = np.dot(n_b, n_b)
ab = np.dot(n_a, n_b)
d_ = 1./(aa*bb - ab*ab)
l_0 = (da*bb - db*ab)*d_*n_a + (db*aa - da*ab)*d_*n_b
return l_v, l_0
def small_circle_intersection(axis_a, angle_a, axis_b, angle_b):
"""
Finds the intersection between two small-circles returning zero, one or two
solutions as tuple.
Parameters:
axis_a: Vector defining first circle axis
angle_a: Small circle aperture angle (in radians) around axis_a
axis_b: Vector defining second circle axis
angle_b: Small circle aperture angle (in radians) around axis_b
"""
line = general_plane_intersection(axis_a, cos(angle_a),
axis_b, cos(angle_b))
if line is None:
return ()
l_v, l_0 = line
# https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection
b = 2*l_v.dot(l_0)
delta = b*b - 4*(l_0.dot(l_0) - 1)
# Should the answers be normalized?
if delta < 0:
return ()
elif delta == 0:
return -b/2.,
else:
sqrt_delta = sqrt(delta)
return l_0 + l_v*(-b - sqrt_delta)/2., l_0 + l_v*(-b + sqrt_delta)/2.
def <|fim_middle|>(azim, plng, rake):
"""
Returns the rotation matrix that rotates the North vector to the line given
by Azimuth and Plunge and East and Up vectors are rotate clock-wise by Rake
around the rotated North vector.
Parameters:
azim: Line Azimuth from North (degrees).
plng: Line Plunge measured from horizontal (degrees).
rake: Rotation angle around rotated axis (degrees).
"""
# pylint: disable=bad-whitespace
azim, plng, rake = radians(azim), radians(plng), radians(rake)
R1 = np.array((( cos(rake), 0., sin(rake)),
( 0., 1., 0. ),
(-sin(rake), 0., cos(rake))))
R2 = np.array((( 1., 0., 0. ),
( 0., cos(plng), sin(plng)),
( 0., -sin(plng), cos(plng))))
R3 = np.array((( cos(azim), sin(azim), 0. ),
(-sin(azim), cos(azim), 0. ),
( 0., 0., 1. )))
return R3.dot(R2).dot(R1)
def adjust_lines_to_planes(lines, planes):
"""
Project each given line to it's respective plane. Returns the projected
lines as a new LineSet and the angle (in radians) between each line and
plane prior to projection.
Parameters:
lines: A LineSet like object with an array of n Lines
planes: A PlaseSet like object with an array of n Planes
"""
lines = at.LineSet(lines)
planes = at.PlaneSet(planes)
angles = np.zeros(len(lines))
adjusted_lines = np.zeros_like(lines)
for i, (line, plane) in enumerate(zip(lines, planes)):
cos_theta = np.dot(line, plane)
angles[i] = pi/2. - acos(cos_theta)
adjusted_line = line - line*cos_theta
adjusted_lines[i] = adjusted_line/sqrt(np.dot(adjusted_line,
adjusted_line))
return adjusted_lines, angles
<|fim▁end|> | build_rotation_matrix |
<|file_name|>math.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name
from __future__ import absolute_import
from math import acos, cos, pi, radians, sin, sqrt
import auttitude as at
import numpy as np
def normalized_cross(a, b):
"""
Returns the normalized cross product between vectors.
Uses numpy.cross().
Parameters:
a: First vector.
b: Second vector.
"""
c = np.cross(a, b)
length = sqrt(c.dot(c))
return c/length if length > 0 else c
def general_plane_intersection(n_a, da, n_b, db):
"""
Returns a point and direction vector for the line of intersection
of two planes in space, or None if planes are parallel.
Parameters:
n_a: Normal vector to plane A
da: Point of plane A
n_b: Normal vector to plane B
db: Point of plane B
"""
# https://en.wikipedia.org/wiki/Intersection_curve
n_a = np.array(n_a)
n_b = np.array(n_b)
da = np.array(da)
db = np.array(db)
l_v = np.cross(n_a, n_b)
norm_l = sqrt(np.dot(l_v, l_v))
if norm_l == 0:
return None
else:
l_v /= norm_l
aa = np.dot(n_a, n_a)
bb = np.dot(n_b, n_b)
ab = np.dot(n_a, n_b)
d_ = 1./(aa*bb - ab*ab)
l_0 = (da*bb - db*ab)*d_*n_a + (db*aa - da*ab)*d_*n_b
return l_v, l_0
def small_circle_intersection(axis_a, angle_a, axis_b, angle_b):
"""
Finds the intersection between two small-circles returning zero, one or two
solutions as tuple.
Parameters:
axis_a: Vector defining first circle axis
angle_a: Small circle aperture angle (in radians) around axis_a
axis_b: Vector defining second circle axis
angle_b: Small circle aperture angle (in radians) around axis_b
"""
line = general_plane_intersection(axis_a, cos(angle_a),
axis_b, cos(angle_b))
if line is None:
return ()
l_v, l_0 = line
# https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection
b = 2*l_v.dot(l_0)
delta = b*b - 4*(l_0.dot(l_0) - 1)
# Should the answers be normalized?
if delta < 0:
return ()
elif delta == 0:
return -b/2.,
else:
sqrt_delta = sqrt(delta)
return l_0 + l_v*(-b - sqrt_delta)/2., l_0 + l_v*(-b + sqrt_delta)/2.
def build_rotation_matrix(azim, plng, rake):
"""
Returns the rotation matrix that rotates the North vector to the line given
by Azimuth and Plunge and East and Up vectors are rotate clock-wise by Rake
around the rotated North vector.
Parameters:
azim: Line Azimuth from North (degrees).
plng: Line Plunge measured from horizontal (degrees).
rake: Rotation angle around rotated axis (degrees).
"""
# pylint: disable=bad-whitespace
azim, plng, rake = radians(azim), radians(plng), radians(rake)
R1 = np.array((( cos(rake), 0., sin(rake)),
( 0., 1., 0. ),
(-sin(rake), 0., cos(rake))))
R2 = np.array((( 1., 0., 0. ),
( 0., cos(plng), sin(plng)),
( 0., -sin(plng), cos(plng))))
R3 = np.array((( cos(azim), sin(azim), 0. ),
(-sin(azim), cos(azim), 0. ),
( 0., 0., 1. )))
return R3.dot(R2).dot(R1)
def <|fim_middle|>(lines, planes):
"""
Project each given line to it's respective plane. Returns the projected
lines as a new LineSet and the angle (in radians) between each line and
plane prior to projection.
Parameters:
lines: A LineSet like object with an array of n Lines
planes: A PlaseSet like object with an array of n Planes
"""
lines = at.LineSet(lines)
planes = at.PlaneSet(planes)
angles = np.zeros(len(lines))
adjusted_lines = np.zeros_like(lines)
for i, (line, plane) in enumerate(zip(lines, planes)):
cos_theta = np.dot(line, plane)
angles[i] = pi/2. - acos(cos_theta)
adjusted_line = line - line*cos_theta
adjusted_lines[i] = adjusted_line/sqrt(np.dot(adjusted_line,
adjusted_line))
return adjusted_lines, angles
<|fim▁end|> | adjust_lines_to_planes |
<|file_name|>json.py<|end_file_name|><|fim▁begin|>import datetime
import re
import sys
from collections import deque
from decimal import Decimal
from enum import Enum
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from types import GeneratorType
from typing import Any, Callable, Dict, Type, Union
from uuid import UUID
if sys.version_info >= (3, 7):
Pattern = re.Pattern
else:
# python 3.6
Pattern = re.compile('a').__class__<|fim▁hole|>from .types import SecretBytes, SecretStr
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
def isoformat(o: Union[datetime.date, datetime.time]) -> str:
return o.isoformat()
def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
"""
Encodes a Decimal as int of there's no exponent, otherwise float
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
where a integer (but not int typed) is used. Encoding this as a float
results in failed round-tripping between encode and prase.
Our Id type is a prime example of this.
>>> decimal_encoder(Decimal("1.0"))
1.0
>>> decimal_encoder(Decimal("1"))
1
"""
if dec_value.as_tuple().exponent >= 0:
return int(dec_value)
else:
return float(dec_value)
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
bytes: lambda o: o.decode(),
Color: str,
datetime.date: isoformat,
datetime.datetime: isoformat,
datetime.time: isoformat,
datetime.timedelta: lambda td: td.total_seconds(),
Decimal: decimal_encoder,
Enum: lambda o: o.value,
frozenset: list,
deque: list,
GeneratorType: list,
IPv4Address: str,
IPv4Interface: str,
IPv4Network: str,
IPv6Address: str,
IPv6Interface: str,
IPv6Network: str,
Path: str,
Pattern: lambda o: o.pattern,
SecretBytes: str,
SecretStr: str,
set: list,
UUID: str,
}
def pydantic_encoder(obj: Any) -> Any:
from dataclasses import asdict, is_dataclass
from .main import BaseModel
if isinstance(obj, BaseModel):
return obj.dict()
elif is_dataclass(obj):
return asdict(obj)
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = ENCODERS_BY_TYPE[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = type_encoders[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
return pydantic_encoder(obj)
def timedelta_isoformat(td: datetime.timedelta) -> str:
"""
ISO 8601 encoding for timedeltas.
"""
minutes, seconds = divmod(td.seconds, 60)
hours, minutes = divmod(minutes, 60)
return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'<|fim▁end|> |
from .color import Color |
<|file_name|>json.py<|end_file_name|><|fim▁begin|>import datetime
import re
import sys
from collections import deque
from decimal import Decimal
from enum import Enum
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from types import GeneratorType
from typing import Any, Callable, Dict, Type, Union
from uuid import UUID
if sys.version_info >= (3, 7):
Pattern = re.Pattern
else:
# python 3.6
Pattern = re.compile('a').__class__
from .color import Color
from .types import SecretBytes, SecretStr
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
def isoformat(o: Union[datetime.date, datetime.time]) -> str:
<|fim_middle|>
def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
"""
Encodes a Decimal as int of there's no exponent, otherwise float
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
where a integer (but not int typed) is used. Encoding this as a float
results in failed round-tripping between encode and prase.
Our Id type is a prime example of this.
>>> decimal_encoder(Decimal("1.0"))
1.0
>>> decimal_encoder(Decimal("1"))
1
"""
if dec_value.as_tuple().exponent >= 0:
return int(dec_value)
else:
return float(dec_value)
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
bytes: lambda o: o.decode(),
Color: str,
datetime.date: isoformat,
datetime.datetime: isoformat,
datetime.time: isoformat,
datetime.timedelta: lambda td: td.total_seconds(),
Decimal: decimal_encoder,
Enum: lambda o: o.value,
frozenset: list,
deque: list,
GeneratorType: list,
IPv4Address: str,
IPv4Interface: str,
IPv4Network: str,
IPv6Address: str,
IPv6Interface: str,
IPv6Network: str,
Path: str,
Pattern: lambda o: o.pattern,
SecretBytes: str,
SecretStr: str,
set: list,
UUID: str,
}
def pydantic_encoder(obj: Any) -> Any:
from dataclasses import asdict, is_dataclass
from .main import BaseModel
if isinstance(obj, BaseModel):
return obj.dict()
elif is_dataclass(obj):
return asdict(obj)
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = ENCODERS_BY_TYPE[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = type_encoders[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
return pydantic_encoder(obj)
def timedelta_isoformat(td: datetime.timedelta) -> str:
"""
ISO 8601 encoding for timedeltas.
"""
minutes, seconds = divmod(td.seconds, 60)
hours, minutes = divmod(minutes, 60)
return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
<|fim▁end|> | return o.isoformat() |
<|file_name|>json.py<|end_file_name|><|fim▁begin|>import datetime
import re
import sys
from collections import deque
from decimal import Decimal
from enum import Enum
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from types import GeneratorType
from typing import Any, Callable, Dict, Type, Union
from uuid import UUID
if sys.version_info >= (3, 7):
Pattern = re.Pattern
else:
# python 3.6
Pattern = re.compile('a').__class__
from .color import Color
from .types import SecretBytes, SecretStr
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
def isoformat(o: Union[datetime.date, datetime.time]) -> str:
return o.isoformat()
def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
<|fim_middle|>
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
bytes: lambda o: o.decode(),
Color: str,
datetime.date: isoformat,
datetime.datetime: isoformat,
datetime.time: isoformat,
datetime.timedelta: lambda td: td.total_seconds(),
Decimal: decimal_encoder,
Enum: lambda o: o.value,
frozenset: list,
deque: list,
GeneratorType: list,
IPv4Address: str,
IPv4Interface: str,
IPv4Network: str,
IPv6Address: str,
IPv6Interface: str,
IPv6Network: str,
Path: str,
Pattern: lambda o: o.pattern,
SecretBytes: str,
SecretStr: str,
set: list,
UUID: str,
}
def pydantic_encoder(obj: Any) -> Any:
from dataclasses import asdict, is_dataclass
from .main import BaseModel
if isinstance(obj, BaseModel):
return obj.dict()
elif is_dataclass(obj):
return asdict(obj)
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = ENCODERS_BY_TYPE[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = type_encoders[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
return pydantic_encoder(obj)
def timedelta_isoformat(td: datetime.timedelta) -> str:
"""
ISO 8601 encoding for timedeltas.
"""
minutes, seconds = divmod(td.seconds, 60)
hours, minutes = divmod(minutes, 60)
return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
<|fim▁end|> | """
Encodes a Decimal as int of there's no exponent, otherwise float
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
where a integer (but not int typed) is used. Encoding this as a float
results in failed round-tripping between encode and prase.
Our Id type is a prime example of this.
>>> decimal_encoder(Decimal("1.0"))
1.0
>>> decimal_encoder(Decimal("1"))
1
"""
if dec_value.as_tuple().exponent >= 0:
return int(dec_value)
else:
return float(dec_value) |
<|file_name|>json.py<|end_file_name|><|fim▁begin|>import datetime
import re
import sys
from collections import deque
from decimal import Decimal
from enum import Enum
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from types import GeneratorType
from typing import Any, Callable, Dict, Type, Union
from uuid import UUID
if sys.version_info >= (3, 7):
Pattern = re.Pattern
else:
# python 3.6
Pattern = re.compile('a').__class__
from .color import Color
from .types import SecretBytes, SecretStr
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
def isoformat(o: Union[datetime.date, datetime.time]) -> str:
return o.isoformat()
def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
"""
Encodes a Decimal as int of there's no exponent, otherwise float
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
where a integer (but not int typed) is used. Encoding this as a float
results in failed round-tripping between encode and prase.
Our Id type is a prime example of this.
>>> decimal_encoder(Decimal("1.0"))
1.0
>>> decimal_encoder(Decimal("1"))
1
"""
if dec_value.as_tuple().exponent >= 0:
return int(dec_value)
else:
return float(dec_value)
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
bytes: lambda o: o.decode(),
Color: str,
datetime.date: isoformat,
datetime.datetime: isoformat,
datetime.time: isoformat,
datetime.timedelta: lambda td: td.total_seconds(),
Decimal: decimal_encoder,
Enum: lambda o: o.value,
frozenset: list,
deque: list,
GeneratorType: list,
IPv4Address: str,
IPv4Interface: str,
IPv4Network: str,
IPv6Address: str,
IPv6Interface: str,
IPv6Network: str,
Path: str,
Pattern: lambda o: o.pattern,
SecretBytes: str,
SecretStr: str,
set: list,
UUID: str,
}
def pydantic_encoder(obj: Any) -> Any:
<|fim_middle|>
def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = type_encoders[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
return pydantic_encoder(obj)
def timedelta_isoformat(td: datetime.timedelta) -> str:
"""
ISO 8601 encoding for timedeltas.
"""
minutes, seconds = divmod(td.seconds, 60)
hours, minutes = divmod(minutes, 60)
return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
<|fim▁end|> | from dataclasses import asdict, is_dataclass
from .main import BaseModel
if isinstance(obj, BaseModel):
return obj.dict()
elif is_dataclass(obj):
return asdict(obj)
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = ENCODERS_BY_TYPE[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable") |
<|file_name|>json.py<|end_file_name|><|fim▁begin|>import datetime
import re
import sys
from collections import deque
from decimal import Decimal
from enum import Enum
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from types import GeneratorType
from typing import Any, Callable, Dict, Type, Union
from uuid import UUID
if sys.version_info >= (3, 7):
Pattern = re.Pattern
else:
# python 3.6
Pattern = re.compile('a').__class__
from .color import Color
from .types import SecretBytes, SecretStr
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
def isoformat(o: Union[datetime.date, datetime.time]) -> str:
return o.isoformat()
def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
"""
Encodes a Decimal as int of there's no exponent, otherwise float
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
where a integer (but not int typed) is used. Encoding this as a float
results in failed round-tripping between encode and prase.
Our Id type is a prime example of this.
>>> decimal_encoder(Decimal("1.0"))
1.0
>>> decimal_encoder(Decimal("1"))
1
"""
if dec_value.as_tuple().exponent >= 0:
return int(dec_value)
else:
return float(dec_value)
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
bytes: lambda o: o.decode(),
Color: str,
datetime.date: isoformat,
datetime.datetime: isoformat,
datetime.time: isoformat,
datetime.timedelta: lambda td: td.total_seconds(),
Decimal: decimal_encoder,
Enum: lambda o: o.value,
frozenset: list,
deque: list,
GeneratorType: list,
IPv4Address: str,
IPv4Interface: str,
IPv4Network: str,
IPv6Address: str,
IPv6Interface: str,
IPv6Network: str,
Path: str,
Pattern: lambda o: o.pattern,
SecretBytes: str,
SecretStr: str,
set: list,
UUID: str,
}
def pydantic_encoder(obj: Any) -> Any:
from dataclasses import asdict, is_dataclass
from .main import BaseModel
if isinstance(obj, BaseModel):
return obj.dict()
elif is_dataclass(obj):
return asdict(obj)
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = ENCODERS_BY_TYPE[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:
# Check the class type and its superclasses for a matching encoder
<|fim_middle|>
def timedelta_isoformat(td: datetime.timedelta) -> str:
"""
ISO 8601 encoding for timedeltas.
"""
minutes, seconds = divmod(td.seconds, 60)
hours, minutes = divmod(minutes, 60)
return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
<|fim▁end|> | for base in obj.__class__.__mro__[:-1]:
try:
encoder = type_encoders[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
return pydantic_encoder(obj) |
<|file_name|>json.py<|end_file_name|><|fim▁begin|>import datetime
import re
import sys
from collections import deque
from decimal import Decimal
from enum import Enum
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from types import GeneratorType
from typing import Any, Callable, Dict, Type, Union
from uuid import UUID
if sys.version_info >= (3, 7):
Pattern = re.Pattern
else:
# python 3.6
Pattern = re.compile('a').__class__
from .color import Color
from .types import SecretBytes, SecretStr
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
def isoformat(o: Union[datetime.date, datetime.time]) -> str:
return o.isoformat()
def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
"""
Encodes a Decimal as int of there's no exponent, otherwise float
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
where a integer (but not int typed) is used. Encoding this as a float
results in failed round-tripping between encode and prase.
Our Id type is a prime example of this.
>>> decimal_encoder(Decimal("1.0"))
1.0
>>> decimal_encoder(Decimal("1"))
1
"""
if dec_value.as_tuple().exponent >= 0:
return int(dec_value)
else:
return float(dec_value)
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
bytes: lambda o: o.decode(),
Color: str,
datetime.date: isoformat,
datetime.datetime: isoformat,
datetime.time: isoformat,
datetime.timedelta: lambda td: td.total_seconds(),
Decimal: decimal_encoder,
Enum: lambda o: o.value,
frozenset: list,
deque: list,
GeneratorType: list,
IPv4Address: str,
IPv4Interface: str,
IPv4Network: str,
IPv6Address: str,
IPv6Interface: str,
IPv6Network: str,
Path: str,
Pattern: lambda o: o.pattern,
SecretBytes: str,
SecretStr: str,
set: list,
UUID: str,
}
def pydantic_encoder(obj: Any) -> Any:
from dataclasses import asdict, is_dataclass
from .main import BaseModel
if isinstance(obj, BaseModel):
return obj.dict()
elif is_dataclass(obj):
return asdict(obj)
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = ENCODERS_BY_TYPE[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = type_encoders[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
return pydantic_encoder(obj)
def timedelta_isoformat(td: datetime.timedelta) -> str:
<|fim_middle|>
<|fim▁end|> | """
ISO 8601 encoding for timedeltas.
"""
minutes, seconds = divmod(td.seconds, 60)
hours, minutes = divmod(minutes, 60)
return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S' |
<|file_name|>json.py<|end_file_name|><|fim▁begin|>import datetime
import re
import sys
from collections import deque
from decimal import Decimal
from enum import Enum
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from types import GeneratorType
from typing import Any, Callable, Dict, Type, Union
from uuid import UUID
if sys.version_info >= (3, 7):
<|fim_middle|>
else:
# python 3.6
Pattern = re.compile('a').__class__
from .color import Color
from .types import SecretBytes, SecretStr
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
def isoformat(o: Union[datetime.date, datetime.time]) -> str:
return o.isoformat()
def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
"""
Encodes a Decimal as int of there's no exponent, otherwise float
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
where a integer (but not int typed) is used. Encoding this as a float
results in failed round-tripping between encode and prase.
Our Id type is a prime example of this.
>>> decimal_encoder(Decimal("1.0"))
1.0
>>> decimal_encoder(Decimal("1"))
1
"""
if dec_value.as_tuple().exponent >= 0:
return int(dec_value)
else:
return float(dec_value)
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
bytes: lambda o: o.decode(),
Color: str,
datetime.date: isoformat,
datetime.datetime: isoformat,
datetime.time: isoformat,
datetime.timedelta: lambda td: td.total_seconds(),
Decimal: decimal_encoder,
Enum: lambda o: o.value,
frozenset: list,
deque: list,
GeneratorType: list,
IPv4Address: str,
IPv4Interface: str,
IPv4Network: str,
IPv6Address: str,
IPv6Interface: str,
IPv6Network: str,
Path: str,
Pattern: lambda o: o.pattern,
SecretBytes: str,
SecretStr: str,
set: list,
UUID: str,
}
def pydantic_encoder(obj: Any) -> Any:
from dataclasses import asdict, is_dataclass
from .main import BaseModel
if isinstance(obj, BaseModel):
return obj.dict()
elif is_dataclass(obj):
return asdict(obj)
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = ENCODERS_BY_TYPE[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = type_encoders[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
return pydantic_encoder(obj)
def timedelta_isoformat(td: datetime.timedelta) -> str:
"""
ISO 8601 encoding for timedeltas.
"""
minutes, seconds = divmod(td.seconds, 60)
hours, minutes = divmod(minutes, 60)
return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
<|fim▁end|> | Pattern = re.Pattern |
<|file_name|>json.py<|end_file_name|><|fim▁begin|>import datetime
import re
import sys
from collections import deque
from decimal import Decimal
from enum import Enum
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from types import GeneratorType
from typing import Any, Callable, Dict, Type, Union
from uuid import UUID
if sys.version_info >= (3, 7):
Pattern = re.Pattern
else:
# python 3.6
<|fim_middle|>
from .color import Color
from .types import SecretBytes, SecretStr
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
def isoformat(o: Union[datetime.date, datetime.time]) -> str:
return o.isoformat()
def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
"""
Encodes a Decimal as int of there's no exponent, otherwise float
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
where a integer (but not int typed) is used. Encoding this as a float
results in failed round-tripping between encode and prase.
Our Id type is a prime example of this.
>>> decimal_encoder(Decimal("1.0"))
1.0
>>> decimal_encoder(Decimal("1"))
1
"""
if dec_value.as_tuple().exponent >= 0:
return int(dec_value)
else:
return float(dec_value)
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
bytes: lambda o: o.decode(),
Color: str,
datetime.date: isoformat,
datetime.datetime: isoformat,
datetime.time: isoformat,
datetime.timedelta: lambda td: td.total_seconds(),
Decimal: decimal_encoder,
Enum: lambda o: o.value,
frozenset: list,
deque: list,
GeneratorType: list,
IPv4Address: str,
IPv4Interface: str,
IPv4Network: str,
IPv6Address: str,
IPv6Interface: str,
IPv6Network: str,
Path: str,
Pattern: lambda o: o.pattern,
SecretBytes: str,
SecretStr: str,
set: list,
UUID: str,
}
def pydantic_encoder(obj: Any) -> Any:
from dataclasses import asdict, is_dataclass
from .main import BaseModel
if isinstance(obj, BaseModel):
return obj.dict()
elif is_dataclass(obj):
return asdict(obj)
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = ENCODERS_BY_TYPE[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = type_encoders[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
return pydantic_encoder(obj)
def timedelta_isoformat(td: datetime.timedelta) -> str:
"""
ISO 8601 encoding for timedeltas.
"""
minutes, seconds = divmod(td.seconds, 60)
hours, minutes = divmod(minutes, 60)
return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
<|fim▁end|> | Pattern = re.compile('a').__class__ |
<|file_name|>json.py<|end_file_name|><|fim▁begin|>import datetime
import re
import sys
from collections import deque
from decimal import Decimal
from enum import Enum
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from types import GeneratorType
from typing import Any, Callable, Dict, Type, Union
from uuid import UUID
if sys.version_info >= (3, 7):
Pattern = re.Pattern
else:
# python 3.6
Pattern = re.compile('a').__class__
from .color import Color
from .types import SecretBytes, SecretStr
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
def isoformat(o: Union[datetime.date, datetime.time]) -> str:
return o.isoformat()
def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
"""
Encodes a Decimal as int of there's no exponent, otherwise float
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
where a integer (but not int typed) is used. Encoding this as a float
results in failed round-tripping between encode and prase.
Our Id type is a prime example of this.
>>> decimal_encoder(Decimal("1.0"))
1.0
>>> decimal_encoder(Decimal("1"))
1
"""
if dec_value.as_tuple().exponent >= 0:
<|fim_middle|>
else:
return float(dec_value)
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
bytes: lambda o: o.decode(),
Color: str,
datetime.date: isoformat,
datetime.datetime: isoformat,
datetime.time: isoformat,
datetime.timedelta: lambda td: td.total_seconds(),
Decimal: decimal_encoder,
Enum: lambda o: o.value,
frozenset: list,
deque: list,
GeneratorType: list,
IPv4Address: str,
IPv4Interface: str,
IPv4Network: str,
IPv6Address: str,
IPv6Interface: str,
IPv6Network: str,
Path: str,
Pattern: lambda o: o.pattern,
SecretBytes: str,
SecretStr: str,
set: list,
UUID: str,
}
def pydantic_encoder(obj: Any) -> Any:
from dataclasses import asdict, is_dataclass
from .main import BaseModel
if isinstance(obj, BaseModel):
return obj.dict()
elif is_dataclass(obj):
return asdict(obj)
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = ENCODERS_BY_TYPE[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = type_encoders[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
return pydantic_encoder(obj)
def timedelta_isoformat(td: datetime.timedelta) -> str:
"""
ISO 8601 encoding for timedeltas.
"""
minutes, seconds = divmod(td.seconds, 60)
hours, minutes = divmod(minutes, 60)
return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
<|fim▁end|> | return int(dec_value) |
<|file_name|>json.py<|end_file_name|><|fim▁begin|>import datetime
import re
import sys
from collections import deque
from decimal import Decimal
from enum import Enum
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from types import GeneratorType
from typing import Any, Callable, Dict, Type, Union
from uuid import UUID
if sys.version_info >= (3, 7):
Pattern = re.Pattern
else:
# python 3.6
Pattern = re.compile('a').__class__
from .color import Color
from .types import SecretBytes, SecretStr
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
def isoformat(o: Union[datetime.date, datetime.time]) -> str:
return o.isoformat()
def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
"""
Encodes a Decimal as int of there's no exponent, otherwise float
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
where a integer (but not int typed) is used. Encoding this as a float
results in failed round-tripping between encode and prase.
Our Id type is a prime example of this.
>>> decimal_encoder(Decimal("1.0"))
1.0
>>> decimal_encoder(Decimal("1"))
1
"""
if dec_value.as_tuple().exponent >= 0:
return int(dec_value)
else:
<|fim_middle|>
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
bytes: lambda o: o.decode(),
Color: str,
datetime.date: isoformat,
datetime.datetime: isoformat,
datetime.time: isoformat,
datetime.timedelta: lambda td: td.total_seconds(),
Decimal: decimal_encoder,
Enum: lambda o: o.value,
frozenset: list,
deque: list,
GeneratorType: list,
IPv4Address: str,
IPv4Interface: str,
IPv4Network: str,
IPv6Address: str,
IPv6Interface: str,
IPv6Network: str,
Path: str,
Pattern: lambda o: o.pattern,
SecretBytes: str,
SecretStr: str,
set: list,
UUID: str,
}
def pydantic_encoder(obj: Any) -> Any:
from dataclasses import asdict, is_dataclass
from .main import BaseModel
if isinstance(obj, BaseModel):
return obj.dict()
elif is_dataclass(obj):
return asdict(obj)
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = ENCODERS_BY_TYPE[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = type_encoders[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
return pydantic_encoder(obj)
def timedelta_isoformat(td: datetime.timedelta) -> str:
"""
ISO 8601 encoding for timedeltas.
"""
minutes, seconds = divmod(td.seconds, 60)
hours, minutes = divmod(minutes, 60)
return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
<|fim▁end|> | return float(dec_value) |
<|file_name|>json.py<|end_file_name|><|fim▁begin|>import datetime
import re
import sys
from collections import deque
from decimal import Decimal
from enum import Enum
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from types import GeneratorType
from typing import Any, Callable, Dict, Type, Union
from uuid import UUID
if sys.version_info >= (3, 7):
Pattern = re.Pattern
else:
# python 3.6
Pattern = re.compile('a').__class__
from .color import Color
from .types import SecretBytes, SecretStr
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
def isoformat(o: Union[datetime.date, datetime.time]) -> str:
return o.isoformat()
def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
"""
Encodes a Decimal as int of there's no exponent, otherwise float
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
where a integer (but not int typed) is used. Encoding this as a float
results in failed round-tripping between encode and prase.
Our Id type is a prime example of this.
>>> decimal_encoder(Decimal("1.0"))
1.0
>>> decimal_encoder(Decimal("1"))
1
"""
if dec_value.as_tuple().exponent >= 0:
return int(dec_value)
else:
return float(dec_value)
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
bytes: lambda o: o.decode(),
Color: str,
datetime.date: isoformat,
datetime.datetime: isoformat,
datetime.time: isoformat,
datetime.timedelta: lambda td: td.total_seconds(),
Decimal: decimal_encoder,
Enum: lambda o: o.value,
frozenset: list,
deque: list,
GeneratorType: list,
IPv4Address: str,
IPv4Interface: str,
IPv4Network: str,
IPv6Address: str,
IPv6Interface: str,
IPv6Network: str,
Path: str,
Pattern: lambda o: o.pattern,
SecretBytes: str,
SecretStr: str,
set: list,
UUID: str,
}
def pydantic_encoder(obj: Any) -> Any:
from dataclasses import asdict, is_dataclass
from .main import BaseModel
if isinstance(obj, BaseModel):
<|fim_middle|>
elif is_dataclass(obj):
return asdict(obj)
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = ENCODERS_BY_TYPE[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = type_encoders[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
return pydantic_encoder(obj)
def timedelta_isoformat(td: datetime.timedelta) -> str:
"""
ISO 8601 encoding for timedeltas.
"""
minutes, seconds = divmod(td.seconds, 60)
hours, minutes = divmod(minutes, 60)
return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
<|fim▁end|> | return obj.dict() |
<|file_name|>json.py<|end_file_name|><|fim▁begin|>import datetime
import re
import sys
from collections import deque
from decimal import Decimal
from enum import Enum
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from types import GeneratorType
from typing import Any, Callable, Dict, Type, Union
from uuid import UUID
if sys.version_info >= (3, 7):
Pattern = re.Pattern
else:
# python 3.6
Pattern = re.compile('a').__class__
from .color import Color
from .types import SecretBytes, SecretStr
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
def isoformat(o: Union[datetime.date, datetime.time]) -> str:
return o.isoformat()
def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
"""
Encodes a Decimal as int of there's no exponent, otherwise float
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
where a integer (but not int typed) is used. Encoding this as a float
results in failed round-tripping between encode and prase.
Our Id type is a prime example of this.
>>> decimal_encoder(Decimal("1.0"))
1.0
>>> decimal_encoder(Decimal("1"))
1
"""
if dec_value.as_tuple().exponent >= 0:
return int(dec_value)
else:
return float(dec_value)
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
bytes: lambda o: o.decode(),
Color: str,
datetime.date: isoformat,
datetime.datetime: isoformat,
datetime.time: isoformat,
datetime.timedelta: lambda td: td.total_seconds(),
Decimal: decimal_encoder,
Enum: lambda o: o.value,
frozenset: list,
deque: list,
GeneratorType: list,
IPv4Address: str,
IPv4Interface: str,
IPv4Network: str,
IPv6Address: str,
IPv6Interface: str,
IPv6Network: str,
Path: str,
Pattern: lambda o: o.pattern,
SecretBytes: str,
SecretStr: str,
set: list,
UUID: str,
}
def pydantic_encoder(obj: Any) -> Any:
from dataclasses import asdict, is_dataclass
from .main import BaseModel
if isinstance(obj, BaseModel):
return obj.dict()
elif is_dataclass(obj):
<|fim_middle|>
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = ENCODERS_BY_TYPE[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = type_encoders[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
return pydantic_encoder(obj)
def timedelta_isoformat(td: datetime.timedelta) -> str:
"""
ISO 8601 encoding for timedeltas.
"""
minutes, seconds = divmod(td.seconds, 60)
hours, minutes = divmod(minutes, 60)
return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
<|fim▁end|> | return asdict(obj) |
<|file_name|>json.py<|end_file_name|><|fim▁begin|>import datetime
import re
import sys
from collections import deque
from decimal import Decimal
from enum import Enum
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from types import GeneratorType
from typing import Any, Callable, Dict, Type, Union
from uuid import UUID
if sys.version_info >= (3, 7):
Pattern = re.Pattern
else:
# python 3.6
Pattern = re.compile('a').__class__
from .color import Color
from .types import SecretBytes, SecretStr
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
def isoformat(o: Union[datetime.date, datetime.time]) -> str:
return o.isoformat()
def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
"""
Encodes a Decimal as int of there's no exponent, otherwise float
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
where a integer (but not int typed) is used. Encoding this as a float
results in failed round-tripping between encode and prase.
Our Id type is a prime example of this.
>>> decimal_encoder(Decimal("1.0"))
1.0
>>> decimal_encoder(Decimal("1"))
1
"""
if dec_value.as_tuple().exponent >= 0:
return int(dec_value)
else:
return float(dec_value)
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
bytes: lambda o: o.decode(),
Color: str,
datetime.date: isoformat,
datetime.datetime: isoformat,
datetime.time: isoformat,
datetime.timedelta: lambda td: td.total_seconds(),
Decimal: decimal_encoder,
Enum: lambda o: o.value,
frozenset: list,
deque: list,
GeneratorType: list,
IPv4Address: str,
IPv4Interface: str,
IPv4Network: str,
IPv6Address: str,
IPv6Interface: str,
IPv6Network: str,
Path: str,
Pattern: lambda o: o.pattern,
SecretBytes: str,
SecretStr: str,
set: list,
UUID: str,
}
def pydantic_encoder(obj: Any) -> Any:
from dataclasses import asdict, is_dataclass
from .main import BaseModel
if isinstance(obj, BaseModel):
return obj.dict()
elif is_dataclass(obj):
return asdict(obj)
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = ENCODERS_BY_TYPE[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
<|fim_middle|>
def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = type_encoders[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
return pydantic_encoder(obj)
def timedelta_isoformat(td: datetime.timedelta) -> str:
"""
ISO 8601 encoding for timedeltas.
"""
minutes, seconds = divmod(td.seconds, 60)
hours, minutes = divmod(minutes, 60)
return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
<|fim▁end|> | raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable") |
<|file_name|>json.py<|end_file_name|><|fim▁begin|>import datetime
import re
import sys
from collections import deque
from decimal import Decimal
from enum import Enum
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from types import GeneratorType
from typing import Any, Callable, Dict, Type, Union
from uuid import UUID
if sys.version_info >= (3, 7):
Pattern = re.Pattern
else:
# python 3.6
Pattern = re.compile('a').__class__
from .color import Color
from .types import SecretBytes, SecretStr
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
def isoformat(o: Union[datetime.date, datetime.time]) -> str:
return o.isoformat()
def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
"""
Encodes a Decimal as int of there's no exponent, otherwise float
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
where a integer (but not int typed) is used. Encoding this as a float
results in failed round-tripping between encode and prase.
Our Id type is a prime example of this.
>>> decimal_encoder(Decimal("1.0"))
1.0
>>> decimal_encoder(Decimal("1"))
1
"""
if dec_value.as_tuple().exponent >= 0:
return int(dec_value)
else:
return float(dec_value)
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
bytes: lambda o: o.decode(),
Color: str,
datetime.date: isoformat,
datetime.datetime: isoformat,
datetime.time: isoformat,
datetime.timedelta: lambda td: td.total_seconds(),
Decimal: decimal_encoder,
Enum: lambda o: o.value,
frozenset: list,
deque: list,
GeneratorType: list,
IPv4Address: str,
IPv4Interface: str,
IPv4Network: str,
IPv6Address: str,
IPv6Interface: str,
IPv6Network: str,
Path: str,
Pattern: lambda o: o.pattern,
SecretBytes: str,
SecretStr: str,
set: list,
UUID: str,
}
def pydantic_encoder(obj: Any) -> Any:
from dataclasses import asdict, is_dataclass
from .main import BaseModel
if isinstance(obj, BaseModel):
return obj.dict()
elif is_dataclass(obj):
return asdict(obj)
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = ENCODERS_BY_TYPE[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = type_encoders[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
<|fim_middle|>
def timedelta_isoformat(td: datetime.timedelta) -> str:
"""
ISO 8601 encoding for timedeltas.
"""
minutes, seconds = divmod(td.seconds, 60)
hours, minutes = divmod(minutes, 60)
return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
<|fim▁end|> | return pydantic_encoder(obj) |
<|file_name|>json.py<|end_file_name|><|fim▁begin|>import datetime
import re
import sys
from collections import deque
from decimal import Decimal
from enum import Enum
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from types import GeneratorType
from typing import Any, Callable, Dict, Type, Union
from uuid import UUID
if sys.version_info >= (3, 7):
Pattern = re.Pattern
else:
# python 3.6
Pattern = re.compile('a').__class__
from .color import Color
from .types import SecretBytes, SecretStr
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
def <|fim_middle|>(o: Union[datetime.date, datetime.time]) -> str:
return o.isoformat()
def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
"""
Encodes a Decimal as int of there's no exponent, otherwise float
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
where a integer (but not int typed) is used. Encoding this as a float
results in failed round-tripping between encode and prase.
Our Id type is a prime example of this.
>>> decimal_encoder(Decimal("1.0"))
1.0
>>> decimal_encoder(Decimal("1"))
1
"""
if dec_value.as_tuple().exponent >= 0:
return int(dec_value)
else:
return float(dec_value)
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
bytes: lambda o: o.decode(),
Color: str,
datetime.date: isoformat,
datetime.datetime: isoformat,
datetime.time: isoformat,
datetime.timedelta: lambda td: td.total_seconds(),
Decimal: decimal_encoder,
Enum: lambda o: o.value,
frozenset: list,
deque: list,
GeneratorType: list,
IPv4Address: str,
IPv4Interface: str,
IPv4Network: str,
IPv6Address: str,
IPv6Interface: str,
IPv6Network: str,
Path: str,
Pattern: lambda o: o.pattern,
SecretBytes: str,
SecretStr: str,
set: list,
UUID: str,
}
def pydantic_encoder(obj: Any) -> Any:
from dataclasses import asdict, is_dataclass
from .main import BaseModel
if isinstance(obj, BaseModel):
return obj.dict()
elif is_dataclass(obj):
return asdict(obj)
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = ENCODERS_BY_TYPE[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = type_encoders[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
return pydantic_encoder(obj)
def timedelta_isoformat(td: datetime.timedelta) -> str:
"""
ISO 8601 encoding for timedeltas.
"""
minutes, seconds = divmod(td.seconds, 60)
hours, minutes = divmod(minutes, 60)
return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
<|fim▁end|> | isoformat |
<|file_name|>json.py<|end_file_name|><|fim▁begin|>import datetime
import re
import sys
from collections import deque
from decimal import Decimal
from enum import Enum
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from types import GeneratorType
from typing import Any, Callable, Dict, Type, Union
from uuid import UUID
if sys.version_info >= (3, 7):
Pattern = re.Pattern
else:
# python 3.6
Pattern = re.compile('a').__class__
from .color import Color
from .types import SecretBytes, SecretStr
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
def isoformat(o: Union[datetime.date, datetime.time]) -> str:
return o.isoformat()
def <|fim_middle|>(dec_value: Decimal) -> Union[int, float]:
"""
Encodes a Decimal as int of there's no exponent, otherwise float
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
where a integer (but not int typed) is used. Encoding this as a float
results in failed round-tripping between encode and prase.
Our Id type is a prime example of this.
>>> decimal_encoder(Decimal("1.0"))
1.0
>>> decimal_encoder(Decimal("1"))
1
"""
if dec_value.as_tuple().exponent >= 0:
return int(dec_value)
else:
return float(dec_value)
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
bytes: lambda o: o.decode(),
Color: str,
datetime.date: isoformat,
datetime.datetime: isoformat,
datetime.time: isoformat,
datetime.timedelta: lambda td: td.total_seconds(),
Decimal: decimal_encoder,
Enum: lambda o: o.value,
frozenset: list,
deque: list,
GeneratorType: list,
IPv4Address: str,
IPv4Interface: str,
IPv4Network: str,
IPv6Address: str,
IPv6Interface: str,
IPv6Network: str,
Path: str,
Pattern: lambda o: o.pattern,
SecretBytes: str,
SecretStr: str,
set: list,
UUID: str,
}
def pydantic_encoder(obj: Any) -> Any:
from dataclasses import asdict, is_dataclass
from .main import BaseModel
if isinstance(obj, BaseModel):
return obj.dict()
elif is_dataclass(obj):
return asdict(obj)
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = ENCODERS_BY_TYPE[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = type_encoders[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
return pydantic_encoder(obj)
def timedelta_isoformat(td: datetime.timedelta) -> str:
"""
ISO 8601 encoding for timedeltas.
"""
minutes, seconds = divmod(td.seconds, 60)
hours, minutes = divmod(minutes, 60)
return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
<|fim▁end|> | decimal_encoder |
<|file_name|>json.py<|end_file_name|><|fim▁begin|>import datetime
import re
import sys
from collections import deque
from decimal import Decimal
from enum import Enum
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from types import GeneratorType
from typing import Any, Callable, Dict, Type, Union
from uuid import UUID
if sys.version_info >= (3, 7):
Pattern = re.Pattern
else:
# python 3.6
Pattern = re.compile('a').__class__
from .color import Color
from .types import SecretBytes, SecretStr
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
def isoformat(o: Union[datetime.date, datetime.time]) -> str:
return o.isoformat()
def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
"""
Encodes a Decimal as int of there's no exponent, otherwise float
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
where a integer (but not int typed) is used. Encoding this as a float
results in failed round-tripping between encode and prase.
Our Id type is a prime example of this.
>>> decimal_encoder(Decimal("1.0"))
1.0
>>> decimal_encoder(Decimal("1"))
1
"""
if dec_value.as_tuple().exponent >= 0:
return int(dec_value)
else:
return float(dec_value)
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
bytes: lambda o: o.decode(),
Color: str,
datetime.date: isoformat,
datetime.datetime: isoformat,
datetime.time: isoformat,
datetime.timedelta: lambda td: td.total_seconds(),
Decimal: decimal_encoder,
Enum: lambda o: o.value,
frozenset: list,
deque: list,
GeneratorType: list,
IPv4Address: str,
IPv4Interface: str,
IPv4Network: str,
IPv6Address: str,
IPv6Interface: str,
IPv6Network: str,
Path: str,
Pattern: lambda o: o.pattern,
SecretBytes: str,
SecretStr: str,
set: list,
UUID: str,
}
def <|fim_middle|>(obj: Any) -> Any:
from dataclasses import asdict, is_dataclass
from .main import BaseModel
if isinstance(obj, BaseModel):
return obj.dict()
elif is_dataclass(obj):
return asdict(obj)
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = ENCODERS_BY_TYPE[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = type_encoders[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
return pydantic_encoder(obj)
def timedelta_isoformat(td: datetime.timedelta) -> str:
"""
ISO 8601 encoding for timedeltas.
"""
minutes, seconds = divmod(td.seconds, 60)
hours, minutes = divmod(minutes, 60)
return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
<|fim▁end|> | pydantic_encoder |
<|file_name|>json.py<|end_file_name|><|fim▁begin|>import datetime
import re
import sys
from collections import deque
from decimal import Decimal
from enum import Enum
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from types import GeneratorType
from typing import Any, Callable, Dict, Type, Union
from uuid import UUID
if sys.version_info >= (3, 7):
Pattern = re.Pattern
else:
# python 3.6
Pattern = re.compile('a').__class__
from .color import Color
from .types import SecretBytes, SecretStr
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
def isoformat(o: Union[datetime.date, datetime.time]) -> str:
return o.isoformat()
def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
"""
Encodes a Decimal as int of there's no exponent, otherwise float
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
where a integer (but not int typed) is used. Encoding this as a float
results in failed round-tripping between encode and prase.
Our Id type is a prime example of this.
>>> decimal_encoder(Decimal("1.0"))
1.0
>>> decimal_encoder(Decimal("1"))
1
"""
if dec_value.as_tuple().exponent >= 0:
return int(dec_value)
else:
return float(dec_value)
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
bytes: lambda o: o.decode(),
Color: str,
datetime.date: isoformat,
datetime.datetime: isoformat,
datetime.time: isoformat,
datetime.timedelta: lambda td: td.total_seconds(),
Decimal: decimal_encoder,
Enum: lambda o: o.value,
frozenset: list,
deque: list,
GeneratorType: list,
IPv4Address: str,
IPv4Interface: str,
IPv4Network: str,
IPv6Address: str,
IPv6Interface: str,
IPv6Network: str,
Path: str,
Pattern: lambda o: o.pattern,
SecretBytes: str,
SecretStr: str,
set: list,
UUID: str,
}
def pydantic_encoder(obj: Any) -> Any:
from dataclasses import asdict, is_dataclass
from .main import BaseModel
if isinstance(obj, BaseModel):
return obj.dict()
elif is_dataclass(obj):
return asdict(obj)
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = ENCODERS_BY_TYPE[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
def <|fim_middle|>(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = type_encoders[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
return pydantic_encoder(obj)
def timedelta_isoformat(td: datetime.timedelta) -> str:
"""
ISO 8601 encoding for timedeltas.
"""
minutes, seconds = divmod(td.seconds, 60)
hours, minutes = divmod(minutes, 60)
return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
<|fim▁end|> | custom_pydantic_encoder |
<|file_name|>json.py<|end_file_name|><|fim▁begin|>import datetime
import re
import sys
from collections import deque
from decimal import Decimal
from enum import Enum
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from types import GeneratorType
from typing import Any, Callable, Dict, Type, Union
from uuid import UUID
if sys.version_info >= (3, 7):
Pattern = re.Pattern
else:
# python 3.6
Pattern = re.compile('a').__class__
from .color import Color
from .types import SecretBytes, SecretStr
__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'
def isoformat(o: Union[datetime.date, datetime.time]) -> str:
return o.isoformat()
def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
"""
Encodes a Decimal as int of there's no exponent, otherwise float
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
where a integer (but not int typed) is used. Encoding this as a float
results in failed round-tripping between encode and prase.
Our Id type is a prime example of this.
>>> decimal_encoder(Decimal("1.0"))
1.0
>>> decimal_encoder(Decimal("1"))
1
"""
if dec_value.as_tuple().exponent >= 0:
return int(dec_value)
else:
return float(dec_value)
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
bytes: lambda o: o.decode(),
Color: str,
datetime.date: isoformat,
datetime.datetime: isoformat,
datetime.time: isoformat,
datetime.timedelta: lambda td: td.total_seconds(),
Decimal: decimal_encoder,
Enum: lambda o: o.value,
frozenset: list,
deque: list,
GeneratorType: list,
IPv4Address: str,
IPv4Interface: str,
IPv4Network: str,
IPv6Address: str,
IPv6Interface: str,
IPv6Network: str,
Path: str,
Pattern: lambda o: o.pattern,
SecretBytes: str,
SecretStr: str,
set: list,
UUID: str,
}
def pydantic_encoder(obj: Any) -> Any:
from dataclasses import asdict, is_dataclass
from .main import BaseModel
if isinstance(obj, BaseModel):
return obj.dict()
elif is_dataclass(obj):
return asdict(obj)
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = ENCODERS_BY_TYPE[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable")
def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:
# Check the class type and its superclasses for a matching encoder
for base in obj.__class__.__mro__[:-1]:
try:
encoder = type_encoders[base]
except KeyError:
continue
return encoder(obj)
else: # We have exited the for loop without finding a suitable encoder
return pydantic_encoder(obj)
def <|fim_middle|>(td: datetime.timedelta) -> str:
"""
ISO 8601 encoding for timedeltas.
"""
minutes, seconds = divmod(td.seconds, 60)
hours, minutes = divmod(minutes, 60)
return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
<|fim▁end|> | timedelta_isoformat |
<|file_name|>test_init.py<|end_file_name|><|fim▁begin|>import pytest
from umodbus.server.serial import AbstractSerialServer
<|fim▁hole|>def abstract_serial_server():
return AbstractSerialServer()
def test_abstract_serial_server_get_meta_data(abstract_serial_server):
""" Test if meta data is correctly extracted from request. """
assert abstract_serial_server.get_meta_data(b'\x01x\02\x03') ==\
{'unit_id': 1}
def test_abract_serial_server_shutdown(abstract_serial_server):
assert abstract_serial_server._shutdown_request is False
abstract_serial_server.shutdown()
assert abstract_serial_server._shutdown_request is True<|fim▁end|> | @pytest.fixture |
<|file_name|>test_init.py<|end_file_name|><|fim▁begin|>import pytest
from umodbus.server.serial import AbstractSerialServer
@pytest.fixture
def abstract_serial_server():
<|fim_middle|>
def test_abstract_serial_server_get_meta_data(abstract_serial_server):
""" Test if meta data is correctly extracted from request. """
assert abstract_serial_server.get_meta_data(b'\x01x\02\x03') ==\
{'unit_id': 1}
def test_abract_serial_server_shutdown(abstract_serial_server):
assert abstract_serial_server._shutdown_request is False
abstract_serial_server.shutdown()
assert abstract_serial_server._shutdown_request is True
<|fim▁end|> | return AbstractSerialServer() |
<|file_name|>test_init.py<|end_file_name|><|fim▁begin|>import pytest
from umodbus.server.serial import AbstractSerialServer
@pytest.fixture
def abstract_serial_server():
return AbstractSerialServer()
def test_abstract_serial_server_get_meta_data(abstract_serial_server):
<|fim_middle|>
def test_abract_serial_server_shutdown(abstract_serial_server):
assert abstract_serial_server._shutdown_request is False
abstract_serial_server.shutdown()
assert abstract_serial_server._shutdown_request is True
<|fim▁end|> | """ Test if meta data is correctly extracted from request. """
assert abstract_serial_server.get_meta_data(b'\x01x\02\x03') ==\
{'unit_id': 1} |
<|file_name|>test_init.py<|end_file_name|><|fim▁begin|>import pytest
from umodbus.server.serial import AbstractSerialServer
@pytest.fixture
def abstract_serial_server():
return AbstractSerialServer()
def test_abstract_serial_server_get_meta_data(abstract_serial_server):
""" Test if meta data is correctly extracted from request. """
assert abstract_serial_server.get_meta_data(b'\x01x\02\x03') ==\
{'unit_id': 1}
def test_abract_serial_server_shutdown(abstract_serial_server):
<|fim_middle|>
<|fim▁end|> | assert abstract_serial_server._shutdown_request is False
abstract_serial_server.shutdown()
assert abstract_serial_server._shutdown_request is True |
<|file_name|>test_init.py<|end_file_name|><|fim▁begin|>import pytest
from umodbus.server.serial import AbstractSerialServer
@pytest.fixture
def <|fim_middle|>():
return AbstractSerialServer()
def test_abstract_serial_server_get_meta_data(abstract_serial_server):
""" Test if meta data is correctly extracted from request. """
assert abstract_serial_server.get_meta_data(b'\x01x\02\x03') ==\
{'unit_id': 1}
def test_abract_serial_server_shutdown(abstract_serial_server):
assert abstract_serial_server._shutdown_request is False
abstract_serial_server.shutdown()
assert abstract_serial_server._shutdown_request is True
<|fim▁end|> | abstract_serial_server |
<|file_name|>test_init.py<|end_file_name|><|fim▁begin|>import pytest
from umodbus.server.serial import AbstractSerialServer
@pytest.fixture
def abstract_serial_server():
return AbstractSerialServer()
def <|fim_middle|>(abstract_serial_server):
""" Test if meta data is correctly extracted from request. """
assert abstract_serial_server.get_meta_data(b'\x01x\02\x03') ==\
{'unit_id': 1}
def test_abract_serial_server_shutdown(abstract_serial_server):
assert abstract_serial_server._shutdown_request is False
abstract_serial_server.shutdown()
assert abstract_serial_server._shutdown_request is True
<|fim▁end|> | test_abstract_serial_server_get_meta_data |
<|file_name|>test_init.py<|end_file_name|><|fim▁begin|>import pytest
from umodbus.server.serial import AbstractSerialServer
@pytest.fixture
def abstract_serial_server():
return AbstractSerialServer()
def test_abstract_serial_server_get_meta_data(abstract_serial_server):
""" Test if meta data is correctly extracted from request. """
assert abstract_serial_server.get_meta_data(b'\x01x\02\x03') ==\
{'unit_id': 1}
def <|fim_middle|>(abstract_serial_server):
assert abstract_serial_server._shutdown_request is False
abstract_serial_server.shutdown()
assert abstract_serial_server._shutdown_request is True
<|fim▁end|> | test_abract_serial_server_shutdown |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€<|fim▁hole|> for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)<|fim▁end|> | if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/') |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
<|fim_middle|>
<|fim▁end|> | api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
|
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
<|fim_middle|>
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url) |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
<|fim_middle|>
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | self.result_msg_for_json = 'JSON:\n\n{}' |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
<|fim_middle|>
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | return DefaultCliArguments(child_parser) |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
<|fim_middle|>
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
<|fim_middle|>
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send) |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
<|fim_middle|>
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
<|fim_middle|>
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code) |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
<|fim_middle|>
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg) |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
<|fim_middle|>
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
<|fim_middle|>
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
|
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
re<|fim_middle|>
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | turn self.result_msg_for_files.format(self.get_processed_output_path())
|
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if<|fim_middle|>
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
|
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
no<|fim_middle|>
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | w = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
|
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
wi<|fim_middle|>
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | th args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
|
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
ap<|fim_middle|>
<|fim▁end|> | i_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
|
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
<|fim_middle|>
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | del args_to_send[arg_to_remove] |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
<|fim_middle|>
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | self.cli_output_folder = args['output']
del args_to_send['output'] |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
<|fim_middle|>
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | del args_to_send['file'] # attaching file is handled by separated method |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
<|fim_middle|>
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | self.api_object.attach_params(args_to_send) |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
<|fim_middle|>
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | self.api_object.attach_data(args_to_send) |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
<|fim_middle|>
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | file = open(file, 'rb') |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
<|fim_middle|>
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type)) |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
<|fim_middle|>
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json())) |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
<|fim_middle|>
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
<|fim_middle|>
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | return self.get_result_msg_for_files() |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
<|fim_middle|>
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
<|fim_middle|>
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')' |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
<|fim_middle|>
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | final_output_path = output_path |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
<|fim_middle|>
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
|
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
ne <|fim_middle|>
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | w_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
|
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
ba <|fim_middle|>
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | d_parts.remove(part)
continue
|
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
fi <|fim_middle|>
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | nal_output_path = '/' + final_output_path
|
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
se <|fim_middle|>
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | lf.save_files()
|
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
ra <|fim_middle|>
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | ise Exception('Given file does not contain any data.')
|
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
id <|fim_middle|>
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | entifier = self.given_args['id']
|
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
id <|fim_middle|>
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | entifier = self.given_args['sha256']
|
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def <|fim_middle|>(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | __init__ |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def <|fim_middle|>(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | init_verbose_mode |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def <|fim_middle|>(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | build_argument_builder |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def <|fim_middle|>(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | add_parser_args |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def <|fim_middle|>(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | attach_args |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def <|fim_middle|>(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | attach_file |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def <|fim_middle|>(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | get_colored_response_status_code |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def <|fim_middle|>(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | get_colored_prepared_response_msg |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def <|fim_middle|>(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | get_result_msg |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def <|fim_middle|>(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | get_processed_output_path |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def ge<|fim_middle|>elf):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | t_result_msg_for_files(s |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do<|fim_middle|>elf):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | _post_processing(s |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def ge<|fim_middle|>elf):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | t_date_string(s |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def co<|fim_middle|>elf, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | nvert_file_hashes_to_array(s |
<|file_name|>cli_caller.py<|end_file_name|><|fim▁begin|>from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def sa<|fim_middle|>elf):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
<|fim▁end|> | ve_files(s |
<|file_name|>test_build_auxiliary_coordinate.py<|end_file_name|><|fim▁begin|># (C) British Crown Copyright 2014 - 2015, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Iris is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#<|fim▁hole|>fc_rules_cf_fc.build_auxilliary_coordinate`.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
# import iris tests first so that some things can be initialised before
# importing anything else
import iris.tests as tests
import numpy as np
import mock
from iris.coords import AuxCoord
from iris.fileformats._pyke_rules.compiled_krb.fc_rules_cf_fc import \
build_auxiliary_coordinate
class TestBoundsVertexDim(tests.IrisTest):
def setUp(self):
# Create coordinate cf variables and pyke engine.
points = np.arange(6).reshape(2, 3)
self.cf_coord_var = mock.Mock(
dimensions=('foo', 'bar'),
cf_name='wibble',
standard_name=None,
long_name='wibble',
units='m',
shape=points.shape,
dtype=points.dtype,
__getitem__=lambda self, key: points[key])
self.engine = mock.Mock(
cube=mock.Mock(),
cf_var=mock.Mock(dimensions=('foo', 'bar')),
filename='DUMMY',
provides=dict(coordinates=[]))
# Create patch for deferred loading that prevents attempted
# file access. This assumes that self.cf_bounds_var is
# defined in the test case.
def patched__getitem__(proxy_self, keys):
variable = None
for var in (self.cf_coord_var, self.cf_bounds_var):
if proxy_self.variable_name == var.cf_name:
return var[keys]
raise RuntimeError()
self.deferred_load_patch = mock.patch(
'iris.fileformats.netcdf.NetCDFDataProxy.__getitem__',
new=patched__getitem__)
def test_slowest_varying_vertex_dim(self):
# Create the bounds cf variable.
bounds = np.arange(24).reshape(4, 2, 3)
self.cf_bounds_var = mock.Mock(
dimensions=('nv', 'foo', 'bar'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
# Expected bounds on the resulting coordinate should be rolled so that
# the vertex dimension is at the end.
expected_bounds = np.rollaxis(bounds, 0, bounds.ndim)
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=expected_bounds)
# Patch the helper function that retrieves the bounds cf variable.
# This avoids the need for setting up further mocking of cf objects.
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
def test_fastest_varying_vertex_dim(self):
bounds = np.arange(24).reshape(2, 3, 4)
self.cf_bounds_var = mock.Mock(
dimensions=('foo', 'bar', 'nv'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=bounds)
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
def test_fastest_with_different_dim_names(self):
# Despite the dimension names ('x', and 'y') differing from the coord's
# which are 'foo' and 'bar' (as permitted by the cf spec),
# this should still work because the vertex dim is the fastest varying.
bounds = np.arange(24).reshape(2, 3, 4)
self.cf_bounds_var = mock.Mock(
dimensions=('x', 'y', 'nv'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=bounds)
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
if __name__ == '__main__':
tests.main()<|fim▁end|> | # You should have received a copy of the GNU Lesser General Public License
# along with Iris. If not, see <http://www.gnu.org/licenses/>.
"""
Test function :func:`iris.fileformats._pyke_rules.compiled_krb.\ |
<|file_name|>test_build_auxiliary_coordinate.py<|end_file_name|><|fim▁begin|># (C) British Crown Copyright 2014 - 2015, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Iris is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Iris. If not, see <http://www.gnu.org/licenses/>.
"""
Test function :func:`iris.fileformats._pyke_rules.compiled_krb.\
fc_rules_cf_fc.build_auxilliary_coordinate`.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
# import iris tests first so that some things can be initialised before
# importing anything else
import iris.tests as tests
import numpy as np
import mock
from iris.coords import AuxCoord
from iris.fileformats._pyke_rules.compiled_krb.fc_rules_cf_fc import \
build_auxiliary_coordinate
class TestBoundsVertexDim(tests.IrisTest):
<|fim_middle|>
if __name__ == '__main__':
tests.main()
<|fim▁end|> | def setUp(self):
# Create coordinate cf variables and pyke engine.
points = np.arange(6).reshape(2, 3)
self.cf_coord_var = mock.Mock(
dimensions=('foo', 'bar'),
cf_name='wibble',
standard_name=None,
long_name='wibble',
units='m',
shape=points.shape,
dtype=points.dtype,
__getitem__=lambda self, key: points[key])
self.engine = mock.Mock(
cube=mock.Mock(),
cf_var=mock.Mock(dimensions=('foo', 'bar')),
filename='DUMMY',
provides=dict(coordinates=[]))
# Create patch for deferred loading that prevents attempted
# file access. This assumes that self.cf_bounds_var is
# defined in the test case.
def patched__getitem__(proxy_self, keys):
variable = None
for var in (self.cf_coord_var, self.cf_bounds_var):
if proxy_self.variable_name == var.cf_name:
return var[keys]
raise RuntimeError()
self.deferred_load_patch = mock.patch(
'iris.fileformats.netcdf.NetCDFDataProxy.__getitem__',
new=patched__getitem__)
def test_slowest_varying_vertex_dim(self):
# Create the bounds cf variable.
bounds = np.arange(24).reshape(4, 2, 3)
self.cf_bounds_var = mock.Mock(
dimensions=('nv', 'foo', 'bar'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
# Expected bounds on the resulting coordinate should be rolled so that
# the vertex dimension is at the end.
expected_bounds = np.rollaxis(bounds, 0, bounds.ndim)
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=expected_bounds)
# Patch the helper function that retrieves the bounds cf variable.
# This avoids the need for setting up further mocking of cf objects.
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
def test_fastest_varying_vertex_dim(self):
bounds = np.arange(24).reshape(2, 3, 4)
self.cf_bounds_var = mock.Mock(
dimensions=('foo', 'bar', 'nv'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=bounds)
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
def test_fastest_with_different_dim_names(self):
# Despite the dimension names ('x', and 'y') differing from the coord's
# which are 'foo' and 'bar' (as permitted by the cf spec),
# this should still work because the vertex dim is the fastest varying.
bounds = np.arange(24).reshape(2, 3, 4)
self.cf_bounds_var = mock.Mock(
dimensions=('x', 'y', 'nv'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=bounds)
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list) |
<|file_name|>test_build_auxiliary_coordinate.py<|end_file_name|><|fim▁begin|># (C) British Crown Copyright 2014 - 2015, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Iris is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Iris. If not, see <http://www.gnu.org/licenses/>.
"""
Test function :func:`iris.fileformats._pyke_rules.compiled_krb.\
fc_rules_cf_fc.build_auxilliary_coordinate`.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
# import iris tests first so that some things can be initialised before
# importing anything else
import iris.tests as tests
import numpy as np
import mock
from iris.coords import AuxCoord
from iris.fileformats._pyke_rules.compiled_krb.fc_rules_cf_fc import \
build_auxiliary_coordinate
class TestBoundsVertexDim(tests.IrisTest):
def setUp(self):
# Create coordinate cf variables and pyke engine.
<|fim_middle|>
def test_slowest_varying_vertex_dim(self):
# Create the bounds cf variable.
bounds = np.arange(24).reshape(4, 2, 3)
self.cf_bounds_var = mock.Mock(
dimensions=('nv', 'foo', 'bar'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
# Expected bounds on the resulting coordinate should be rolled so that
# the vertex dimension is at the end.
expected_bounds = np.rollaxis(bounds, 0, bounds.ndim)
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=expected_bounds)
# Patch the helper function that retrieves the bounds cf variable.
# This avoids the need for setting up further mocking of cf objects.
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
def test_fastest_varying_vertex_dim(self):
bounds = np.arange(24).reshape(2, 3, 4)
self.cf_bounds_var = mock.Mock(
dimensions=('foo', 'bar', 'nv'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=bounds)
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
def test_fastest_with_different_dim_names(self):
# Despite the dimension names ('x', and 'y') differing from the coord's
# which are 'foo' and 'bar' (as permitted by the cf spec),
# this should still work because the vertex dim is the fastest varying.
bounds = np.arange(24).reshape(2, 3, 4)
self.cf_bounds_var = mock.Mock(
dimensions=('x', 'y', 'nv'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=bounds)
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
if __name__ == '__main__':
tests.main()
<|fim▁end|> | points = np.arange(6).reshape(2, 3)
self.cf_coord_var = mock.Mock(
dimensions=('foo', 'bar'),
cf_name='wibble',
standard_name=None,
long_name='wibble',
units='m',
shape=points.shape,
dtype=points.dtype,
__getitem__=lambda self, key: points[key])
self.engine = mock.Mock(
cube=mock.Mock(),
cf_var=mock.Mock(dimensions=('foo', 'bar')),
filename='DUMMY',
provides=dict(coordinates=[]))
# Create patch for deferred loading that prevents attempted
# file access. This assumes that self.cf_bounds_var is
# defined in the test case.
def patched__getitem__(proxy_self, keys):
variable = None
for var in (self.cf_coord_var, self.cf_bounds_var):
if proxy_self.variable_name == var.cf_name:
return var[keys]
raise RuntimeError()
self.deferred_load_patch = mock.patch(
'iris.fileformats.netcdf.NetCDFDataProxy.__getitem__',
new=patched__getitem__) |
<|file_name|>test_build_auxiliary_coordinate.py<|end_file_name|><|fim▁begin|># (C) British Crown Copyright 2014 - 2015, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Iris is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Iris. If not, see <http://www.gnu.org/licenses/>.
"""
Test function :func:`iris.fileformats._pyke_rules.compiled_krb.\
fc_rules_cf_fc.build_auxilliary_coordinate`.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
# import iris tests first so that some things can be initialised before
# importing anything else
import iris.tests as tests
import numpy as np
import mock
from iris.coords import AuxCoord
from iris.fileformats._pyke_rules.compiled_krb.fc_rules_cf_fc import \
build_auxiliary_coordinate
class TestBoundsVertexDim(tests.IrisTest):
def setUp(self):
# Create coordinate cf variables and pyke engine.
points = np.arange(6).reshape(2, 3)
self.cf_coord_var = mock.Mock(
dimensions=('foo', 'bar'),
cf_name='wibble',
standard_name=None,
long_name='wibble',
units='m',
shape=points.shape,
dtype=points.dtype,
__getitem__=lambda self, key: points[key])
self.engine = mock.Mock(
cube=mock.Mock(),
cf_var=mock.Mock(dimensions=('foo', 'bar')),
filename='DUMMY',
provides=dict(coordinates=[]))
# Create patch for deferred loading that prevents attempted
# file access. This assumes that self.cf_bounds_var is
# defined in the test case.
def patched__getitem__(proxy_self, keys):
<|fim_middle|>
self.deferred_load_patch = mock.patch(
'iris.fileformats.netcdf.NetCDFDataProxy.__getitem__',
new=patched__getitem__)
def test_slowest_varying_vertex_dim(self):
# Create the bounds cf variable.
bounds = np.arange(24).reshape(4, 2, 3)
self.cf_bounds_var = mock.Mock(
dimensions=('nv', 'foo', 'bar'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
# Expected bounds on the resulting coordinate should be rolled so that
# the vertex dimension is at the end.
expected_bounds = np.rollaxis(bounds, 0, bounds.ndim)
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=expected_bounds)
# Patch the helper function that retrieves the bounds cf variable.
# This avoids the need for setting up further mocking of cf objects.
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
def test_fastest_varying_vertex_dim(self):
bounds = np.arange(24).reshape(2, 3, 4)
self.cf_bounds_var = mock.Mock(
dimensions=('foo', 'bar', 'nv'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=bounds)
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
def test_fastest_with_different_dim_names(self):
# Despite the dimension names ('x', and 'y') differing from the coord's
# which are 'foo' and 'bar' (as permitted by the cf spec),
# this should still work because the vertex dim is the fastest varying.
bounds = np.arange(24).reshape(2, 3, 4)
self.cf_bounds_var = mock.Mock(
dimensions=('x', 'y', 'nv'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=bounds)
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
if __name__ == '__main__':
tests.main()
<|fim▁end|> | variable = None
for var in (self.cf_coord_var, self.cf_bounds_var):
if proxy_self.variable_name == var.cf_name:
return var[keys]
raise RuntimeError() |
<|file_name|>test_build_auxiliary_coordinate.py<|end_file_name|><|fim▁begin|># (C) British Crown Copyright 2014 - 2015, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Iris is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Iris. If not, see <http://www.gnu.org/licenses/>.
"""
Test function :func:`iris.fileformats._pyke_rules.compiled_krb.\
fc_rules_cf_fc.build_auxilliary_coordinate`.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
# import iris tests first so that some things can be initialised before
# importing anything else
import iris.tests as tests
import numpy as np
import mock
from iris.coords import AuxCoord
from iris.fileformats._pyke_rules.compiled_krb.fc_rules_cf_fc import \
build_auxiliary_coordinate
class TestBoundsVertexDim(tests.IrisTest):
def setUp(self):
# Create coordinate cf variables and pyke engine.
points = np.arange(6).reshape(2, 3)
self.cf_coord_var = mock.Mock(
dimensions=('foo', 'bar'),
cf_name='wibble',
standard_name=None,
long_name='wibble',
units='m',
shape=points.shape,
dtype=points.dtype,
__getitem__=lambda self, key: points[key])
self.engine = mock.Mock(
cube=mock.Mock(),
cf_var=mock.Mock(dimensions=('foo', 'bar')),
filename='DUMMY',
provides=dict(coordinates=[]))
# Create patch for deferred loading that prevents attempted
# file access. This assumes that self.cf_bounds_var is
# defined in the test case.
def patched__getitem__(proxy_self, keys):
variable = None
for var in (self.cf_coord_var, self.cf_bounds_var):
if proxy_self.variable_name == var.cf_name:
return var[keys]
raise RuntimeError()
self.deferred_load_patch = mock.patch(
'iris.fileformats.netcdf.NetCDFDataProxy.__getitem__',
new=patched__getitem__)
def test_slowest_varying_vertex_dim(self):
# Create the bounds cf variable.
<|fim_middle|>
def test_fastest_varying_vertex_dim(self):
bounds = np.arange(24).reshape(2, 3, 4)
self.cf_bounds_var = mock.Mock(
dimensions=('foo', 'bar', 'nv'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=bounds)
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
def test_fastest_with_different_dim_names(self):
# Despite the dimension names ('x', and 'y') differing from the coord's
# which are 'foo' and 'bar' (as permitted by the cf spec),
# this should still work because the vertex dim is the fastest varying.
bounds = np.arange(24).reshape(2, 3, 4)
self.cf_bounds_var = mock.Mock(
dimensions=('x', 'y', 'nv'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=bounds)
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
if __name__ == '__main__':
tests.main()
<|fim▁end|> | bounds = np.arange(24).reshape(4, 2, 3)
self.cf_bounds_var = mock.Mock(
dimensions=('nv', 'foo', 'bar'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
# Expected bounds on the resulting coordinate should be rolled so that
# the vertex dimension is at the end.
expected_bounds = np.rollaxis(bounds, 0, bounds.ndim)
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=expected_bounds)
# Patch the helper function that retrieves the bounds cf variable.
# This avoids the need for setting up further mocking of cf objects.
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list) |
<|file_name|>test_build_auxiliary_coordinate.py<|end_file_name|><|fim▁begin|># (C) British Crown Copyright 2014 - 2015, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Iris is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Iris. If not, see <http://www.gnu.org/licenses/>.
"""
Test function :func:`iris.fileformats._pyke_rules.compiled_krb.\
fc_rules_cf_fc.build_auxilliary_coordinate`.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
# import iris tests first so that some things can be initialised before
# importing anything else
import iris.tests as tests
import numpy as np
import mock
from iris.coords import AuxCoord
from iris.fileformats._pyke_rules.compiled_krb.fc_rules_cf_fc import \
build_auxiliary_coordinate
class TestBoundsVertexDim(tests.IrisTest):
def setUp(self):
# Create coordinate cf variables and pyke engine.
points = np.arange(6).reshape(2, 3)
self.cf_coord_var = mock.Mock(
dimensions=('foo', 'bar'),
cf_name='wibble',
standard_name=None,
long_name='wibble',
units='m',
shape=points.shape,
dtype=points.dtype,
__getitem__=lambda self, key: points[key])
self.engine = mock.Mock(
cube=mock.Mock(),
cf_var=mock.Mock(dimensions=('foo', 'bar')),
filename='DUMMY',
provides=dict(coordinates=[]))
# Create patch for deferred loading that prevents attempted
# file access. This assumes that self.cf_bounds_var is
# defined in the test case.
def patched__getitem__(proxy_self, keys):
variable = None
for var in (self.cf_coord_var, self.cf_bounds_var):
if proxy_self.variable_name == var.cf_name:
return var[keys]
raise RuntimeError()
self.deferred_load_patch = mock.patch(
'iris.fileformats.netcdf.NetCDFDataProxy.__getitem__',
new=patched__getitem__)
def test_slowest_varying_vertex_dim(self):
# Create the bounds cf variable.
bounds = np.arange(24).reshape(4, 2, 3)
self.cf_bounds_var = mock.Mock(
dimensions=('nv', 'foo', 'bar'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
# Expected bounds on the resulting coordinate should be rolled so that
# the vertex dimension is at the end.
expected_bounds = np.rollaxis(bounds, 0, bounds.ndim)
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=expected_bounds)
# Patch the helper function that retrieves the bounds cf variable.
# This avoids the need for setting up further mocking of cf objects.
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
def test_fastest_varying_vertex_dim(self):
<|fim_middle|>
def test_fastest_with_different_dim_names(self):
# Despite the dimension names ('x', and 'y') differing from the coord's
# which are 'foo' and 'bar' (as permitted by the cf spec),
# this should still work because the vertex dim is the fastest varying.
bounds = np.arange(24).reshape(2, 3, 4)
self.cf_bounds_var = mock.Mock(
dimensions=('x', 'y', 'nv'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=bounds)
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
if __name__ == '__main__':
tests.main()
<|fim▁end|> | bounds = np.arange(24).reshape(2, 3, 4)
self.cf_bounds_var = mock.Mock(
dimensions=('foo', 'bar', 'nv'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=bounds)
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list) |
<|file_name|>test_build_auxiliary_coordinate.py<|end_file_name|><|fim▁begin|># (C) British Crown Copyright 2014 - 2015, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Iris is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Iris. If not, see <http://www.gnu.org/licenses/>.
"""
Test function :func:`iris.fileformats._pyke_rules.compiled_krb.\
fc_rules_cf_fc.build_auxilliary_coordinate`.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
# import iris tests first so that some things can be initialised before
# importing anything else
import iris.tests as tests
import numpy as np
import mock
from iris.coords import AuxCoord
from iris.fileformats._pyke_rules.compiled_krb.fc_rules_cf_fc import \
build_auxiliary_coordinate
class TestBoundsVertexDim(tests.IrisTest):
def setUp(self):
# Create coordinate cf variables and pyke engine.
points = np.arange(6).reshape(2, 3)
self.cf_coord_var = mock.Mock(
dimensions=('foo', 'bar'),
cf_name='wibble',
standard_name=None,
long_name='wibble',
units='m',
shape=points.shape,
dtype=points.dtype,
__getitem__=lambda self, key: points[key])
self.engine = mock.Mock(
cube=mock.Mock(),
cf_var=mock.Mock(dimensions=('foo', 'bar')),
filename='DUMMY',
provides=dict(coordinates=[]))
# Create patch for deferred loading that prevents attempted
# file access. This assumes that self.cf_bounds_var is
# defined in the test case.
def patched__getitem__(proxy_self, keys):
variable = None
for var in (self.cf_coord_var, self.cf_bounds_var):
if proxy_self.variable_name == var.cf_name:
return var[keys]
raise RuntimeError()
self.deferred_load_patch = mock.patch(
'iris.fileformats.netcdf.NetCDFDataProxy.__getitem__',
new=patched__getitem__)
def test_slowest_varying_vertex_dim(self):
# Create the bounds cf variable.
bounds = np.arange(24).reshape(4, 2, 3)
self.cf_bounds_var = mock.Mock(
dimensions=('nv', 'foo', 'bar'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
# Expected bounds on the resulting coordinate should be rolled so that
# the vertex dimension is at the end.
expected_bounds = np.rollaxis(bounds, 0, bounds.ndim)
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=expected_bounds)
# Patch the helper function that retrieves the bounds cf variable.
# This avoids the need for setting up further mocking of cf objects.
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
def test_fastest_varying_vertex_dim(self):
bounds = np.arange(24).reshape(2, 3, 4)
self.cf_bounds_var = mock.Mock(
dimensions=('foo', 'bar', 'nv'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=bounds)
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
def test_fastest_with_different_dim_names(self):
# Despite the dimension names ('x', and 'y') differing from the coord's
# which are 'foo' and 'bar' (as permitted by the cf spec),
# this should still work because the vertex dim is the fastest varying.
<|fim_middle|>
if __name__ == '__main__':
tests.main()
<|fim▁end|> | bounds = np.arange(24).reshape(2, 3, 4)
self.cf_bounds_var = mock.Mock(
dimensions=('x', 'y', 'nv'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=bounds)
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.