def get_path_line_number(self, path, with_attrs=False):
path = path.split("| ")[1] if (with_attrs is True) else path
orig = self.parsed
path = get_dict_from_path(path, self.separator)
res = traverse_and_remove_path(orig, path)
orig = json.dumps(orig, indent=4).split("\n")
if(len(orig) != self.file_line_number):
raise ValueError("This json file formatting is not compatible. Please run `python -m json.tool file`")
with_del = json.dumps(res, indent=4).split("\n")
return(list_compare_idx(orig, with_del) + 1)
python类tool()的实例源码
def main():
prog = 'python -m json.tool'
description = ('A simple command line interface for json module '
'to validate and pretty-print JSON objects.')
parser = argparse.ArgumentParser(prog=prog, description=description)
parser.add_argument('infile', nargs='?', type=argparse.FileType(),
help='a JSON file to be validated or pretty-printed')
parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
help='write the output of infile to outfile')
parser.add_argument('--sort-keys', action='store_true', default=False,
help='sort the output of dictionaries alphabetically by key')
options = parser.parse_args()
infile = options.infile or sys.stdin
outfile = options.outfile or sys.stdout
sort_keys = options.sort_keys
with infile:
try:
if sort_keys:
obj = json.load(infile)
else:
obj = json.load(infile,
object_pairs_hook=collections.OrderedDict)
except ValueError as e:
raise SystemExit(e)
with outfile:
json.dump(obj, outfile, sort_keys=sort_keys, indent=4)
outfile.write('\n')
def yahoo_stock_info(self, ticker):
r = requests.get('http://finance.yahoo.com/quote/AAPL?p=' + ticker)
soup = BeautifulSoup(r.text)
tables = soup.find_all('table')[1:] # drop the first useless table
# curl 'https://query2.finance.yahoo.com/v10/finance/quoteSummary/AAPL?modules=summaryProfile%2CfinancialData%2CrecommendationTrend%2CupgradeDowngradeHistory%2Cearnings%2CdefaultKeyStatistics%2CcalendarEvents' | python -m json.tool > tmp2.txt
print(soup.prettify())
import pytest
pytest.set_trace()
def del_speaker(self, **kwargs):
"""
Shutdowns BGPSpeaker instance.
Usage:
======= ================
Method URI
======= ================
DELETE /vtep/speakers
======= ================
Example::
$ curl -X DELETE http://localhost:8080/vtep/speakers |
python -m json.tool
::
{
"172.17.0.1": {
"EvpnSpeaker": {
"as_number": 65000,
"dpid": 1,
"neighbors": {},
"router_id": "172.17.0.1"
}
}
}
"""
try:
body = self.vtep_app.del_speaker()
except BGPSpeakerNotFound as e:
return e.to_response(status=404)
return Response(content_type='application/json',
body=json.dumps(body))
def get_neighbors(self, **kwargs):
"""
Gets a list of all neighbors.
Usage:
======= ========================
Method URI
======= ========================
GET /vtep/neighbors
======= ========================
Example::
$ curl -X GET http://localhost:8080/vtep/neighbors |
python -m json.tool
::
{
"172.17.0.2": {
"EvpnNeighbor": {
"address": "172.17.0.2",
"remote_as": 65000,
"state": "up"
}
}
}
"""
return self._get_neighbors(**kwargs)
def get_networks(self, **kwargs):
"""
Gets a list of all networks.
Usage:
======= ===============
Method URI
======= ===============
GET /vtep/networks
======= ===============
Example::
$ curl -X GET http://localhost:8080/vtep/networks |
python -m json.tool
::
{
"10": {
"EvpnNetwork": {
"clients": {
"aa:bb:cc:dd:ee:ff": {
"EvpnClient": {
"ip": "10.0.0.1",
"mac": "aa:bb:cc:dd:ee:ff",
"next_hop": "172.17.0.1",
"port": 1
}
}
},
"ethernet_tag_id": 0,
"route_dist": "65000:10",
"vni": 10
}
}
}
"""
return self._get_networks(**kwargs)
def main():
prog = 'python -m json.tool'
description = ('A simple command line interface for json module '
'to validate and pretty-print JSON objects.')
parser = argparse.ArgumentParser(prog=prog, description=description)
parser.add_argument('infile', nargs='?', type=argparse.FileType(),
help='a JSON file to be validated or pretty-printed')
parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
help='write the output of infile to outfile')
parser.add_argument('--sort-keys', action='store_true', default=False,
help='sort the output of dictionaries alphabetically by key')
options = parser.parse_args()
infile = options.infile or sys.stdin
outfile = options.outfile or sys.stdout
sort_keys = options.sort_keys
with infile:
try:
if sort_keys:
obj = json.load(infile)
else:
obj = json.load(infile,
object_pairs_hook=collections.OrderedDict)
except ValueError as e:
raise SystemExit(e)
with outfile:
json.dump(obj, outfile, sort_keys=sort_keys, indent=4)
outfile.write('\n')
def add_speaker(self, **kwargs):
"""
Creates a new BGPSpeaker instance.
Usage:
======= ================
Method URI
======= ================
POST /vtep/speakers
======= ================
Request parameters:
========== ============================================
Attribute Description
========== ============================================
dpid ID of Datapath binding to speaker. (e.g. 1)
as_number AS number. (e.g. 65000)
router_id Router ID. (e.g. "172.17.0.1")
========== ============================================
Example::
$ curl -X POST -d '{
"dpid": 1,
"as_number": 65000,
"router_id": "172.17.0.1"
}' http://localhost:8080/vtep/speakers | python -m json.tool
::
{
"172.17.0.1": {
"EvpnSpeaker": {
"as_number": 65000,
"dpid": 1,
"neighbors": {},
"router_id": "172.17.0.1"
}
}
}
"""
try:
body = self.vtep_app.add_speaker(**kwargs)
except DatapathNotFound as e:
return e.to_response(status=404)
return Response(content_type='application/json',
body=json.dumps(body))
def get_speakers(self, **kwargs):
"""
Gets the info of BGPSpeaker instance.
Usage:
======= ================
Method URI
======= ================
GET /vtep/speakers
======= ================
Example::
$ curl -X GET http://localhost:8080/vtep/speakers |
python -m json.tool
::
{
"172.17.0.1": {
"EvpnSpeaker": {
"as_number": 65000,
"dpid": 1,
"neighbors": {
"172.17.0.2": {
"EvpnNeighbor": {
"address": "172.17.0.2",
"remote_as": 65000,
"state": "up"
}
}
},
"router_id": "172.17.0.1"
}
}
}
"""
try:
body = self.vtep_app.get_speaker()
except BGPSpeakerNotFound as e:
return e.to_response(status=404)
return Response(content_type='application/json',
body=json.dumps(body))
def add_neighbor(self, **kwargs):
"""
Registers a new neighbor to the speaker.
Usage:
======= ========================
Method URI
======= ========================
POST /vtep/neighbors
======= ========================
Request parameters:
========== ================================================
Attribute Description
========== ================================================
address IP address of neighbor. (e.g. "172.17.0.2")
remote_as AS number of neighbor. (e.g. 65000)
========== ================================================
Example::
$ curl -X POST -d '{
"address": "172.17.0.2",
"remote_as": 65000
}' http://localhost:8080/vtep/neighbors |
python -m json.tool
::
{
"172.17.0.2": {
"EvpnNeighbor": {
"address": "172.17.0.2",
"remote_as": 65000,
"state": "down"
}
}
}
"""
try:
body = self.vtep_app.add_neighbor(**kwargs)
except BGPSpeakerNotFound as e:
return e.to_response(status=400)
return Response(content_type='application/json',
body=json.dumps(body))
def del_neighbor(self, **kwargs):
"""
Unregister the specified neighbor from the speaker.
Usage:
======= ==================================
Method URI
======= ==================================
DELETE /vtep/speaker/neighbors/{address}
======= ==================================
Request parameters:
========== ================================================
Attribute Description
========== ================================================
address IP address of neighbor. (e.g. "172.17.0.2")
========== ================================================
Example::
$ curl -X DELETE http://localhost:8080/vtep/speaker/neighbors/172.17.0.2 |
python -m json.tool
::
{
"172.17.0.2": {
"EvpnNeighbor": {
"address": "172.17.0.2",
"remote_as": 65000,
"state": "up"
}
}
}
"""
try:
body = self.vtep_app.del_neighbor(**kwargs)
except (BGPSpeakerNotFound, NeighborNotFound) as e:
return e.to_response(status=404)
return Response(content_type='application/json',
body=json.dumps(body))
def add_network(self, **kwargs):
"""
Defines a new network.
Usage:
======= ===============
Method URI
======= ===============
POST /vtep/networks
======= ===============
Request parameters:
================ ========================================
Attribute Description
================ ========================================
vni Virtual Network Identifier. (e.g. 10)
================ ========================================
Example::
$ curl -X POST -d '{
"vni": 10
}' http://localhost:8080/vtep/networks | python -m json.tool
::
{
"10": {
"EvpnNetwork": {
"clients": {},
"ethernet_tag_id": 0,
"route_dist": "65000:10",
"vni": 10
}
}
}
"""
try:
body = self.vtep_app.add_network(**kwargs)
except BGPSpeakerNotFound as e:
return e.to_response(status=404)
return Response(content_type='application/json',
body=json.dumps(body))
def get_network(self, **kwargs):
"""
Gets the network for the specified VNI.
Usage:
======= =====================
Method URI
======= =====================
GET /vtep/networks/{vni}
======= =====================
Request parameters:
================ ========================================
Attribute Description
================ ========================================
vni Virtual Network Identifier. (e.g. 10)
================ ========================================
Example::
$ curl -X GET http://localhost:8080/vtep/networks/10 |
python -m json.tool
::
{
"10": {
"EvpnNetwork": {
"clients": {
"aa:bb:cc:dd:ee:ff": {
"EvpnClient": {
"ip": "10.0.0.1",
"mac": "aa:bb:cc:dd:ee:ff",
"next_hop": "172.17.0.1",
"port": 1
}
}
},
"ethernet_tag_id": 0,
"route_dist": "65000:10",
"vni": 10
}
}
}
"""
return self._get_networks(**kwargs)
def del_network(self, **kwargs):
"""
Deletes the network for the specified VNI.
Usage:
======= =====================
Method URI
======= =====================
DELETE /vtep/networks/{vni}
======= =====================
Request parameters:
================ ========================================
Attribute Description
================ ========================================
vni Virtual Network Identifier. (e.g. 10)
================ ========================================
Example::
$ curl -X DELETE http://localhost:8080/vtep/networks/10 |
python -m json.tool
::
{
"10": {
"EvpnNetwork": {
"ethernet_tag_id": 10,
"clients": [
{
"EvpnClient": {
"ip": "10.0.0.11",
"mac": "e2:b1:0c:ba:42:ed",
"port": 1
}
}
],
"route_dist": "65000:100",
"vni": 10
}
}
}
"""
try:
body = self.vtep_app.del_network(**kwargs)
except (BGPSpeakerNotFound, DatapathNotFound, VniNotFound) as e:
return e.to_response(status=404)
return Response(content_type='application/json',
body=json.dumps(body))
def del_client(self, **kwargs):
"""
Registers a new client to the specified network.
Usage:
======= ===================================
Method URI
======= ===================================
DELETE /vtep/networks/{vni}/clients/{mac}
======= ===================================
Request parameters:
=========== ===============================================
Attribute Description
=========== ===============================================
vni Virtual Network Identifier. (e.g. 10)
mac Client MAC address to register.
=========== ===============================================
Example::
$ curl -X DELETE http://localhost:8080/vtep/networks/10/clients/aa:bb:cc:dd:ee:ff |
python -m json.tool
::
{
"10": {
"EvpnClient": {
"ip": "10.0.0.1",
"mac": "aa:bb:cc:dd:ee:ff",
"next_hop": "172.17.0.1",
"port": 1
}
}
}
"""
try:
body = self.vtep_app.del_client(**kwargs)
except (BGPSpeakerNotFound, DatapathNotFound,
VniNotFound, ClientNotFound, ClientNotLocal) as e:
return Response(body=str(e), status=500)
return Response(content_type='application/json',
body=json.dumps(body))