-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper_tools.py
73 lines (57 loc) · 1.9 KB
/
helper_tools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# Matthieu Landes, EMSC, 22/10/2017
from __future__ import print_function
import requests
from io import BytesIO, StringIO
import csv
import json
import zipfile
import numpy as np
def geturl(url):
"""
Get the ascii content of an URL
"""
res = requests.get(url, timeout=15)
return {'status': res.status_code,
'content': res.text}
def parsecsv(txt, usedict=False):
"""
Parse txt input as csv
the first line may be used to parse input as dictionary
"""
if usedict:
parser = csv.DictReader(StringIO(txt), delimiter='|')
else:
parser = csv.reader(StringIO(txt), delimiter='|')
header = next(parser)
return [line for line in parser]
def parsejson(txt):
"""
Parse txt input as json
"""
return json.loads(txt)
def parsezip(bufferstr):
"""
parse binary object as zip file
This archive is supposed to contain a set of column based file
"""
z = zipfile.ZipFile(BytesIO(bufferstr))
res = {}
for filename in z.namelist():
data = z.read(filename).decode('utf-8')
A = np.loadtxt(StringIO(data), delimiter=',')
res[filename] = A
return res
if __name__ == "__main__":
# basic example in text
print("Web service example using \'text\' format:")
url = "http://www.seismicportal.eu/fdsnws/event/1/query?eventid=20170919_0000091&format=text"
res = geturl(url)
print(parsecsv(res['content']))
print("\nWeb service example using \'json\' format:")
url = "http://www.seismicportal.eu/fdsnws/event/1/query?eventid=20170919_0000091&format=json"
res = geturl(url)
print(parsejson(res['content']))
print("\nWeb service example using \'zip\' format (Felt reports web service):")
url = "http://vigogne.emsc-csem.org/testimonies-ws/api/search?unids=[20170919_0000091]&includeTestimonies=true"
r = requests.get(url, stream=True)
print(parsezip(r.content))