1 | NO CONTENT: modified file, binary diff hidden |
|
NO CONTENT: modified file, binary diff hidden |
@@ -1,935 +1,935 | |||||
1 | from ckanapi import RemoteCKAN |
|
1 | from ckanapi import RemoteCKAN | |
2 | from datetime import datetime |
|
2 | from datetime import datetime | |
3 | from tqdm import tqdm |
|
3 | from tqdm import tqdm | |
4 | #from ckanapi.errors import NotAuthorized, NotFound, ValidationError, SearchQueryError, SearchError, CKANAPIError, ServerIncompatibleError |
|
4 | #from ckanapi.errors import NotAuthorized, NotFound, ValidationError, SearchQueryError, SearchError, CKANAPIError, ServerIncompatibleError | |
5 | import sys |
|
5 | import sys | |
6 | import platform |
|
6 | import platform | |
7 | import os |
|
7 | import os | |
8 | import tempfile |
|
8 | import tempfile | |
9 | import shutil |
|
9 | import shutil | |
10 | import zipfile |
|
10 | import zipfile | |
11 | import concurrent.futures |
|
11 | import concurrent.futures | |
12 | import requests |
|
12 | import requests | |
13 | import json |
|
13 | import json | |
14 | #import pathlib |
|
14 | #import pathlib | |
15 | import uuid |
|
15 | import uuid | |
16 |
|
16 | |||
17 | if sys.version_info.major == 3: |
|
17 | if sys.version_info.major == 3: | |
18 | from urllib.parse import urlparse |
|
18 | from urllib.parse import urlparse | |
19 | else: |
|
19 | else: | |
20 | import urlparse |
|
20 | import urlparse | |
21 |
|
21 | |||
22 | class JROAPI(): |
|
22 | class JROAPI(): | |
23 | """ |
|
23 | """ | |
24 | FINALIDAD: |
|
24 | FINALIDAD: | |
25 | Script para administrar y obtener la data del repositorio por medio de APIs. |
|
25 | Script para administrar y obtener la data del repositorio por medio de APIs. | |
26 |
|
26 | |||
27 | REQUISITIOS PREVIOS: |
|
27 | REQUISITIOS PREVIOS: | |
28 | - Paso 1: Tener "pip [Python 2]" o "pip3 [Python 3]" instalado: |
|
28 | - Paso 1: Tener "pip [Python 2]" o "pip3 [Python 3]" instalado: | |
29 | - Paso 2: Instalar lo siguiente como admininstrador: |
|
29 | - Paso 2: Instalar lo siguiente como admininstrador: | |
30 | En Python 2 |
|
30 | En Python 2 | |
31 | - pip install ckanapi==4.5 |
|
31 | - pip install ckanapi==4.5 | |
32 | - pip install requests |
|
32 | - pip install requests | |
33 | - pip install futures |
|
33 | - pip install futures | |
34 | - pip install tqdm |
|
34 | - pip install tqdm | |
35 | En Python > 3 |
|
35 | En Python > 3 | |
36 | - pip3 install ckanapi==4.5 |
|
36 | - pip3 install ckanapi==4.5 | |
37 | - pip3 install requests |
|
37 | - pip3 install requests | |
38 | - pip3 install tqdm |
|
38 | - pip3 install tqdm | |
39 |
|
39 | |||
40 | FUNCIONES DISPONIBLES: |
|
40 | FUNCIONES DISPONIBLES: | |
41 | - action |
|
41 | - action | |
42 | - upload_file |
|
42 | - upload_file | |
43 | - upload_multiple_files |
|
43 | - upload_multiple_files | |
44 | - upload_multiple_files_advance |
|
44 | - upload_multiple_files_advance | |
45 | - show |
|
45 | - show | |
46 | - search |
|
46 | - search | |
47 | - create |
|
47 | - create | |
48 | - patch |
|
48 | - patch | |
49 | - delete |
|
49 | - delete | |
50 | - download_files |
|
50 | - download_files | |
51 |
|
51 | |||
52 | EJEMPLOS: |
|
52 | EJEMPLOS: | |
53 | #1: |
|
53 | #1: | |
54 | with JROAPI('http://demo.example.com', Authorization='#########') as <access_name>: |
|
54 | with JROAPI('http://demo.example.com', Authorization='#########') as <access_name>: | |
55 | ... some operation(s) ... |
|
55 | ... some operation(s) ... | |
56 | #2: |
|
56 | #2: | |
57 | <access_name> = JROAPI('http://example.com', Authorization='#########') |
|
57 | <access_name> = JROAPI('http://example.com', Authorization='#########') | |
58 | ... some operation(s) ... |
|
58 | ... some operation(s) ... | |
59 | <access_name>.ckan.close() |
|
59 | <access_name>.ckan.close() | |
60 |
|
60 | |||
61 | REPORTAR ALGUN PROBLEMA: |
|
61 | REPORTAR ALGUN PROBLEMA: | |
62 | Debe enviar un correo a eynilupu@igp.gob.pe detallando los siguientes pasos: |
|
62 | Debe enviar un correo a eynilupu@igp.gob.pe detallando los siguientes pasos: | |
63 | 1) Correo para contactarlo |
|
63 | 1) Correo para contactarlo | |
64 | 2) Descripcion del problema |
|
64 | 2) Descripcion del problema | |
65 | 3) ¿En que paso o seccion encontro el problema? |
|
65 | 3) ¿En que paso o seccion encontro el problema? | |
66 | 4) ¿Cual era el resultado que usted esperaba? |
|
66 | 4) ¿Cual era el resultado que usted esperaba? | |
67 | """ |
|
67 | """ | |
68 | def __init__(self, url, Authorization=None): |
|
68 | def __init__(self, url, Authorization=None, secure=True): | |
69 |
#-------- |
|
69 | #-------- Check Secure -------# | |
70 |
self.verify = |
|
70 | self.verify = secure | |
71 | session = None |
|
71 | if not secure and isinstance(secure, bool): | |
72 | if urlparse(url).scheme == 'https': |
|
|||
73 | session = requests.Session() |
|
72 | session = requests.Session() | |
74 | session.verify = False |
|
73 | session.verify = False | |
75 | self.verify = False |
|
74 | else: | |
76 | #--------------------------# |
|
75 | session = None | |
|
76 | #------------------------------# | |||
77 | self.url = url |
|
77 | self.url = url | |
78 | ua = 'CKAN_JRO/2.9.2 (+'+str(self.url)+')' |
|
78 | ua = 'CKAN_JRO/2.9.2 (+'+str(self.url)+')' | |
79 | #ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' |
|
79 | #ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' | |
80 | self.ckan = RemoteCKAN(self.url, apikey=Authorization, user_agent=ua, session=session) |
|
80 | self.ckan = RemoteCKAN(self.url, apikey=Authorization, user_agent=ua, session=session) | |
81 | #self.ckan = RemoteCKAN(self.url, apikey=Authorization) |
|
81 | #self.ckan = RemoteCKAN(self.url, apikey=Authorization) | |
82 | self.Authorization = Authorization |
|
82 | self.Authorization = Authorization | |
83 | # Change for --> self.separator = os.sep |
|
83 | # Change for --> self.separator = os.sep | |
84 | if platform.system() == 'Windows': |
|
84 | if platform.system() == 'Windows': | |
85 | self.separator = '\\' |
|
85 | self.separator = '\\' | |
86 | else: |
|
86 | else: | |
87 | self.separator = '/' |
|
87 | self.separator = '/' | |
88 |
|
88 | |||
89 | self.chunk_size = 1024 |
|
89 | self.chunk_size = 1024 | |
90 | self.list = [] |
|
90 | self.list = [] | |
91 | self.dict = {} |
|
91 | self.dict = {} | |
92 | self.str = '' |
|
92 | self.str = '' | |
93 | self.check = 1 |
|
93 | self.check = 1 | |
94 | self.cont = 0 |
|
94 | self.cont = 0 | |
95 |
|
95 | |||
96 | def __enter__(self): |
|
96 | def __enter__(self): | |
97 | return self |
|
97 | return self | |
98 |
|
98 | |||
99 | def __exit__(self, *args): |
|
99 | def __exit__(self, *args): | |
100 | self.ckan.close() |
|
100 | self.ckan.close() | |
101 |
|
101 | |||
102 | def action(self, action, **kwargs): |
|
102 | def action(self, action, **kwargs): | |
103 | """ |
|
103 | """ | |
104 | FINALIDAD: |
|
104 | FINALIDAD: | |
105 | Funcion para llamar a las APIs disponibles |
|
105 | Funcion para llamar a las APIs disponibles | |
106 |
|
106 | |||
107 | APIs DISPONIBLES: |
|
107 | APIs DISPONIBLES: | |
108 | CONSULTAR: "GUIA DE SCRIPT.pdf" |
|
108 | CONSULTAR: "GUIA DE SCRIPT.pdf" | |
109 |
|
109 | |||
110 | EJEMPLO: |
|
110 | EJEMPLO: | |
111 | <access_name>.action(<consuming API>, param_1 = <class 'param_1'>, ...) |
|
111 | <access_name>.action(<consuming API>, param_1 = <class 'param_1'>, ...) | |
112 | """ |
|
112 | """ | |
113 | #--------------- CASE: PACKAGE SEARCH ---------------# |
|
113 | #--------------- CASE: PACKAGE SEARCH ---------------# | |
114 | if kwargs is not None: |
|
114 | if kwargs is not None: | |
115 | if action == 'package_search': |
|
115 | if action == 'package_search': | |
116 | self.list = ['facet_mincount', 'facet_limit', 'facet_field'] |
|
116 | self.list = ['facet_mincount', 'facet_limit', 'facet_field'] | |
117 | for facet in self.list: |
|
117 | for facet in self.list: | |
118 | if facet in kwargs: |
|
118 | if facet in kwargs: | |
119 | kwargs[facet.replace('_', '.')] = kwargs[facet] |
|
119 | kwargs[facet.replace('_', '.')] = kwargs[facet] | |
120 | kwargs.pop(facet) |
|
120 | kwargs.pop(facet) | |
121 | #----------------------------------------------------# |
|
121 | #----------------------------------------------------# | |
122 | try: |
|
122 | try: | |
123 | return getattr(self.ckan.action, action)(**kwargs) |
|
123 | return getattr(self.ckan.action, action)(**kwargs) | |
124 | except: |
|
124 | except: | |
125 | _, exc_value, _ = sys.exc_info() |
|
125 | _, exc_value, _ = sys.exc_info() | |
126 | return exc_value |
|
126 | return exc_value | |
127 |
|
127 | |||
128 | def upload_file(self, dataset_id, file_path, file_date, file_type, **kwargs): |
|
128 | def upload_file(self, dataset_id, file_path, file_date, file_type, **kwargs): | |
129 | # Agregar si es interruptido por teclado |
|
129 | # Agregar si es interruptido por teclado | |
130 | ''' |
|
130 | ''' | |
131 | FINALIDAD: |
|
131 | FINALIDAD: | |
132 | Funcion para subir un unico archivo al repositorio del ROJ. |
|
132 | Funcion para subir un unico archivo al repositorio del ROJ. | |
133 |
|
133 | |||
134 | PARAMETROS DISPONIBLES: |
|
134 | PARAMETROS DISPONIBLES: | |
135 | CONSULTAR: "GUIA DE SCRIPT.pdf" |
|
135 | CONSULTAR: "GUIA DE SCRIPT.pdf" | |
136 |
|
136 | |||
137 | ESTRUCTURA: |
|
137 | ESTRUCTURA: | |
138 | <access_name>.upload_file(dataset_id = <class 'str'>, file_date = <class 'str'>, file_path = <class 'str'>, file_type = <class 'str'>, param_1 = <class 'param_1'>, ...) |
|
138 | <access_name>.upload_file(dataset_id = <class 'str'>, file_date = <class 'str'>, file_path = <class 'str'>, file_type = <class 'str'>, param_1 = <class 'param_1'>, ...) | |
139 | ''' |
|
139 | ''' | |
140 | self.list = ['package_id', 'upload', 'voc_file_type', 'name'] #file_date |
|
140 | self.list = ['package_id', 'upload', 'voc_file_type', 'name'] #file_date | |
141 | for key1, value1 in kwargs.items(): |
|
141 | for key1, value1 in kwargs.items(): | |
142 | if not key1 in self.list: |
|
142 | if not key1 in self.list: | |
143 | self.dict[key1] = value1 |
|
143 | self.dict[key1] = value1 | |
144 |
|
144 | |||
145 | #---------------------------# |
|
145 | #---------------------------# | |
146 | if not 'others' in kwargs: |
|
146 | if not 'others' in kwargs: | |
147 | self.dict['others'] = '' |
|
147 | self.dict['others'] = '' | |
148 | else: |
|
148 | else: | |
149 | if isinstance(kwargs['others'], list): |
|
149 | if isinstance(kwargs['others'], list): | |
150 | self.dict['others'] = json.dumps(kwargs['others']) |
|
150 | self.dict['others'] = json.dumps(kwargs['others']) | |
151 | #---------------------------# |
|
151 | #---------------------------# | |
152 |
|
152 | |||
153 | if not os.path.isfile(file_path): |
|
153 | if not os.path.isfile(file_path): | |
154 | return 'File "%s" not exist' % (file_path) |
|
154 | return 'File "%s" not exist' % (file_path) | |
155 |
|
155 | |||
156 | #if not 'format' in self.dict: |
|
156 | #if not 'format' in self.dict: | |
157 | # self.str = ''.join(pathlib.Path(file_path).suffixes) |
|
157 | # self.str = ''.join(pathlib.Path(file_path).suffixes) | |
158 | # if len(self.str) > 0: |
|
158 | # if len(self.str) > 0: | |
159 | # self.dict['format'] = self.str.upper()[1:] |
|
159 | # self.dict['format'] = self.str.upper()[1:] | |
160 |
|
160 | |||
161 | #-------------------------PACKAGE SHOW-----------------------# |
|
161 | #-------------------------PACKAGE SHOW-----------------------# | |
162 | try: |
|
162 | try: | |
163 | dataset_show = getattr(self.ckan.action, 'package_show')(id=dataset_id)['resources'] |
|
163 | dataset_show = getattr(self.ckan.action, 'package_show')(id=dataset_id)['resources'] | |
164 | except: |
|
164 | except: | |
165 | _, exc_value, _ = sys.exc_info() |
|
165 | _, exc_value, _ = sys.exc_info() | |
166 | print('ERROR obtaining metadata dataset:: Use the "print" for more information') |
|
166 | print('ERROR obtaining metadata dataset:: Use the "print" for more information') | |
167 | return exc_value |
|
167 | return exc_value | |
168 |
|
168 | |||
169 | resources_name = [] |
|
169 | resources_name = [] | |
170 | for u in dataset_show: |
|
170 | for u in dataset_show: | |
171 | resources_name.append(u['name'].lower()) |
|
171 | resources_name.append(u['name'].lower()) | |
172 |
|
172 | |||
173 | if os.path.basename(file_path).lower() in resources_name: |
|
173 | if os.path.basename(file_path).lower() in resources_name: | |
174 | return 'ERROR:: "%s" file already exist in this dataset' % (os.path.basename(file_path)) |
|
174 | return 'ERROR:: "%s" file already exist in this dataset' % (os.path.basename(file_path)) | |
175 | #------------------------------------------------------------# |
|
175 | #------------------------------------------------------------# | |
176 |
|
176 | |||
177 | try: |
|
177 | try: | |
178 | return getattr(self.ckan.action, 'resource_create')(package_id=dataset_id, file_date=file_date, upload=open(file_path, 'rb'), voc_file_type=file_type, name=os.path.basename(file_path), **self.dict) |
|
178 | return getattr(self.ckan.action, 'resource_create')(package_id=dataset_id, file_date=file_date, upload=open(file_path, 'rb'), voc_file_type=file_type, name=os.path.basename(file_path), **self.dict) | |
179 | except: |
|
179 | except: | |
180 | _, exc_value, _ = sys.exc_info() |
|
180 | _, exc_value, _ = sys.exc_info() | |
181 | return exc_value |
|
181 | return exc_value | |
182 |
|
182 | |||
183 | def upload_multiple_files_advance(self, dataset_id, path_files, file_date, file_type, max_size=100, max_count=500, ignore_repetition=False, **kwargs): |
|
183 | def upload_multiple_files_advance(self, dataset_id, path_files, file_date, file_type, max_size=100, max_count=500, ignore_repetition=False, **kwargs): | |
184 | # Agregar si es interruptido por teclado |
|
184 | # Agregar si es interruptido por teclado | |
185 | ''' |
|
185 | ''' | |
186 | FINALIDAD: |
|
186 | FINALIDAD: | |
187 | Funcion para subir multiples archivos al repositorio del ROJ. |
|
187 | Funcion para subir multiples archivos al repositorio del ROJ. | |
188 |
|
188 | |||
189 | PARAMETROS DISPONIBLES: |
|
189 | PARAMETROS DISPONIBLES: | |
190 | CONSULTAR: "GUIA DE SCRIPT.pdf" |
|
190 | CONSULTAR: "GUIA DE SCRIPT.pdf" | |
191 |
|
191 | |||
192 | ESTRUCTURA: |
|
192 | ESTRUCTURA: | |
193 | <access_name>.upload_multiple_files_advance(dataset_id = <class 'str'>, path_files = <class 'list of strings'>, file_date = <class 'str'>, file_type = <class 'str'>, param_1 = <class 'param_1'>, ...) |
|
193 | <access_name>.upload_multiple_files_advance(dataset_id = <class 'str'>, path_files = <class 'list of strings'>, file_date = <class 'str'>, file_type = <class 'str'>, param_1 = <class 'param_1'>, ...) | |
194 | ''' |
|
194 | ''' | |
195 | #-------------------------PACKAGE SHOW-----------------------# |
|
195 | #-------------------------PACKAGE SHOW-----------------------# | |
196 | try: |
|
196 | try: | |
197 | dataset_show = getattr(self.ckan.action, 'package_show')(id=dataset_id)['resources'] |
|
197 | dataset_show = getattr(self.ckan.action, 'package_show')(id=dataset_id)['resources'] | |
198 | except: |
|
198 | except: | |
199 | _, exc_value, _ = sys.exc_info() |
|
199 | _, exc_value, _ = sys.exc_info() | |
200 | print('ERROR obtaining metadata dataset:: Use the "print" for more information') |
|
200 | print('ERROR obtaining metadata dataset:: Use the "print" for more information') | |
201 | return exc_value |
|
201 | return exc_value | |
202 | #------------------------------------------------------------# |
|
202 | #------------------------------------------------------------# | |
203 | resources_name = [] |
|
203 | resources_name = [] | |
204 | for u in dataset_show: |
|
204 | for u in dataset_show: | |
205 | resources_name.append(u['name'].lower()) |
|
205 | resources_name.append(u['name'].lower()) | |
206 | #------------------------------------------------------------# |
|
206 | #------------------------------------------------------------# | |
207 | self.list = ['package_id', 'upload', 'voc_file_type', 'name'] |
|
207 | self.list = ['package_id', 'upload', 'voc_file_type', 'name'] | |
208 | for key1, value1 in kwargs.items(): |
|
208 | for key1, value1 in kwargs.items(): | |
209 | if not key1 in self.list: |
|
209 | if not key1 in self.list: | |
210 | self.dict[key1] = value1 |
|
210 | self.dict[key1] = value1 | |
211 | #------------------------------------------------------------# |
|
211 | #------------------------------------------------------------# | |
212 | if not 'others' in kwargs: |
|
212 | if not 'others' in kwargs: | |
213 | self.dict['others'] = '' |
|
213 | self.dict['others'] = '' | |
214 | else: |
|
214 | else: | |
215 | if isinstance(kwargs['others'], list): |
|
215 | if isinstance(kwargs['others'], list): | |
216 | self.dict['others'] = json.dumps(kwargs['others']) |
|
216 | self.dict['others'] = json.dumps(kwargs['others']) | |
217 | #------------------------------------------------------------# |
|
217 | #------------------------------------------------------------# | |
218 | total_list = [] |
|
218 | total_list = [] | |
219 | #---------------CASO : "path" or "path_list"-----------------# |
|
219 | #---------------CASO : "path" or "path_list"-----------------# | |
220 | if type(path_files) is list: |
|
220 | if type(path_files) is list: | |
221 | if len(path_files) != 0: |
|
221 | if len(path_files) != 0: | |
222 | path_files.sort() |
|
222 | path_files.sort() | |
223 | for u in path_files: |
|
223 | for u in path_files: | |
224 | if os.path.isfile(u): |
|
224 | if os.path.isfile(u): | |
225 | if os.path.basename(u).lower() in resources_name: |
|
225 | if os.path.basename(u).lower() in resources_name: | |
226 | if not ignore_repetition: |
|
226 | if not ignore_repetition: | |
227 | return 'ERROR:: "%s" file already exist in this dataset' % (os.path.basename(u)) |
|
227 | return 'ERROR:: "%s" file already exist in this dataset' % (os.path.basename(u)) | |
228 | print('WARRING:: "'+ str(os.path.basename(u)) +'" file was ignored because already exist in this dataset') |
|
228 | print('WARRING:: "'+ str(os.path.basename(u)) +'" file was ignored because already exist in this dataset') | |
229 | else: |
|
229 | else: | |
230 | total_list.append({'name':os.path.basename(u), 'size': os.stat(u).st_size, 'upload':open(u, 'rb')}) |
|
230 | total_list.append({'name':os.path.basename(u), 'size': os.stat(u).st_size, 'upload':open(u, 'rb')}) | |
231 | else: |
|
231 | else: | |
232 | return 'File "%s" does not exist' % (u) |
|
232 | return 'File "%s" does not exist' % (u) | |
233 | else: |
|
233 | else: | |
234 | return 'ERROR:: "path_list is empty"' |
|
234 | return 'ERROR:: "path_list is empty"' | |
235 |
|
235 | |||
236 | elif type(path_files) is str: |
|
236 | elif type(path_files) is str: | |
237 | if os.path.isdir(path_files): |
|
237 | if os.path.isdir(path_files): | |
238 | path_order = [f for f in os.listdir(path_files) if os.path.isfile(os.path.join(path_files, f))] |
|
238 | path_order = [f for f in os.listdir(path_files) if os.path.isfile(os.path.join(path_files, f))] | |
239 | path_order.sort() |
|
239 | path_order.sort() | |
240 | if path_order: |
|
240 | if path_order: | |
241 | for name in path_order: |
|
241 | for name in path_order: | |
242 | if name.lower() in resources_name: |
|
242 | if name.lower() in resources_name: | |
243 | if not ignore_repetition: |
|
243 | if not ignore_repetition: | |
244 | return 'ERROR:: "%s" file already exist in this dataset' % (name) |
|
244 | return 'ERROR:: "%s" file already exist in this dataset' % (name) | |
245 | print('WARRING:: "'+ name +'" file was ignored because already exist in this dataset') |
|
245 | print('WARRING:: "'+ name +'" file was ignored because already exist in this dataset') | |
246 | else: |
|
246 | else: | |
247 | total_list.append({'name':name, 'size': os.stat(os.path.join(path_files, name)).st_size, 'upload':open(os.path.join(path_files, name), 'rb')}) |
|
247 | total_list.append({'name':name, 'size': os.stat(os.path.join(path_files, name)).st_size, 'upload':open(os.path.join(path_files, name), 'rb')}) | |
248 | else: |
|
248 | else: | |
249 | return "ERROR:: There aren't files in this directory" |
|
249 | return "ERROR:: There aren't files in this directory" | |
250 | else: |
|
250 | else: | |
251 | return 'ERROR:: Directory "%s" does not exist' % (path_files) |
|
251 | return 'ERROR:: Directory "%s" does not exist' % (path_files) | |
252 | else: |
|
252 | else: | |
253 | return 'ERROR:: "path_files" must be a str or list' |
|
253 | return 'ERROR:: "path_files" must be a str or list' | |
254 | #------------------------------------------------------------# |
|
254 | #------------------------------------------------------------# | |
255 | try: |
|
255 | try: | |
256 | uuid.UUID(str(dataset_id), version=4) |
|
256 | uuid.UUID(str(dataset_id), version=4) | |
257 | package_id_or_name = '"id": "' + str(dataset_id) + '"' |
|
257 | package_id_or_name = '"id": "' + str(dataset_id) + '"' | |
258 | except ValueError: |
|
258 | except ValueError: | |
259 | package_id_or_name = '"name": "' + str(dataset_id) + '"' |
|
259 | package_id_or_name = '"name": "' + str(dataset_id) + '"' | |
260 | #------------------------------------------------------------# |
|
260 | #------------------------------------------------------------# | |
261 | blocks = [[]] |
|
261 | blocks = [[]] | |
262 | size_file = 0 |
|
262 | size_file = 0 | |
263 | count_file = 0 |
|
263 | count_file = 0 | |
264 | inter_num = 0 |
|
264 | inter_num = 0 | |
265 | for value in total_list: |
|
265 | for value in total_list: | |
266 | if value['size'] > 1024 * 1024 * float(max_size): |
|
266 | if value['size'] > 1024 * 1024 * float(max_size): | |
267 | return 'ERROR:: The size of the "%s" file is %sMB aprox, please change "max_size" value' % (value['name'], str(round(value['size']/(1024 * 1024), 2))) |
|
267 | return 'ERROR:: The size of the "%s" file is %sMB aprox, please change "max_size" value' % (value['name'], str(round(value['size']/(1024 * 1024), 2))) | |
268 | if not 1 <= int(max_count) <= 999: |
|
268 | if not 1 <= int(max_count) <= 999: | |
269 | return 'ERROR:: The count of the number of files must be between 1 and 999, please change "max_count" value' |
|
269 | return 'ERROR:: The count of the number of files must be between 1 and 999, please change "max_count" value' | |
270 |
|
270 | |||
271 | size_file = size_file + value['size'] |
|
271 | size_file = size_file + value['size'] | |
272 | count_file = count_file + 1 |
|
272 | count_file = count_file + 1 | |
273 | if size_file <= 1024 * 1024 * float(max_size) and count_file <= int(max_count): |
|
273 | if size_file <= 1024 * 1024 * float(max_size) and count_file <= int(max_count): | |
274 | del value['size'] |
|
274 | del value['size'] | |
275 | blocks[inter_num].append(value) |
|
275 | blocks[inter_num].append(value) | |
276 | else: |
|
276 | else: | |
277 | inter_num = inter_num + 1 |
|
277 | inter_num = inter_num + 1 | |
278 | size_file = value['size'] |
|
278 | size_file = value['size'] | |
279 | count_file = 1 |
|
279 | count_file = 1 | |
280 | blocks.append([]) |
|
280 | blocks.append([]) | |
281 | del value['size'] |
|
281 | del value['size'] | |
282 | blocks[inter_num].append(value) |
|
282 | blocks[inter_num].append(value) | |
283 | #------------------------------------------------------------# |
|
283 | #------------------------------------------------------------# | |
284 | if len(blocks[0]) > 0: |
|
284 | if len(blocks[0]) > 0: | |
285 | print('BLOCK(S) IN TOTAL:: {}'.format(len(blocks))) |
|
285 | print('BLOCK(S) IN TOTAL:: {}'.format(len(blocks))) | |
286 | for count1, block in enumerate(blocks): |
|
286 | for count1, block in enumerate(blocks): | |
287 | print('---- BLOCK N°{} ----'.format(count1 + 1)) |
|
287 | print('---- BLOCK N°{} ----'.format(count1 + 1)) | |
288 | resource_extend = [] |
|
288 | resource_extend = [] | |
289 | files_dict = {} |
|
289 | files_dict = {} | |
290 | for count2, value2 in enumerate(block): |
|
290 | for count2, value2 in enumerate(block): | |
291 | value2['file_date'] = file_date |
|
291 | value2['file_date'] = file_date | |
292 | value2['voc_file_type'] = file_type |
|
292 | value2['voc_file_type'] = file_type | |
293 | value2.update(self.dict) |
|
293 | value2.update(self.dict) | |
294 |
|
294 | |||
295 | #if not 'format' in value2: |
|
295 | #if not 'format' in value2: | |
296 | # format = ''.join(pathlib.Path(value2['name']).suffixes) |
|
296 | # format = ''.join(pathlib.Path(value2['name']).suffixes) | |
297 | # if len(format) > 0: |
|
297 | # if len(format) > 0: | |
298 | # value2['format'] = format.upper()[1:] |
|
298 | # value2['format'] = format.upper()[1:] | |
299 |
|
299 | |||
300 | files_dict['update__resources__-'+ str(len(block)-count2) +'__upload'] = (value2['name'], value2['upload']) |
|
300 | files_dict['update__resources__-'+ str(len(block)-count2) +'__upload'] = (value2['name'], value2['upload']) | |
301 | del value2['upload'] |
|
301 | del value2['upload'] | |
302 | resource_extend.append(value2) |
|
302 | resource_extend.append(value2) | |
303 |
|
303 | |||
304 | print('BLOCK N°{} :: "{}" file(s) found >> uploading'.format(count1 + 1, len(block))) |
|
304 | print('BLOCK N°{} :: "{}" file(s) found >> uploading'.format(count1 + 1, len(block))) | |
305 | try: |
|
305 | try: | |
306 | result = self.ckan.call_action( |
|
306 | result = self.ckan.call_action( | |
307 | 'package_revise', |
|
307 | 'package_revise', | |
308 | {'match': '{'+ str(package_id_or_name) +'}', 'update__resources__extend': json.dumps(resource_extend)}, |
|
308 | {'match': '{'+ str(package_id_or_name) +'}', 'update__resources__extend': json.dumps(resource_extend)}, | |
309 | files=files_dict |
|
309 | files=files_dict | |
310 | ) |
|
310 | ) | |
311 | print('BLOCK N°{} :: Uploaded file(s) successfully'.format(count1 + 1)) |
|
311 | print('BLOCK N°{} :: Uploaded file(s) successfully'.format(count1 + 1)) | |
312 | if len(blocks) == count1 + 1: |
|
312 | if len(blocks) == count1 + 1: | |
313 | return result |
|
313 | return result | |
314 | except: |
|
314 | except: | |
315 | print('ERROR :: Use the "print" for more information') |
|
315 | print('ERROR :: Use the "print" for more information') | |
316 | _, exc_value, _ = sys.exc_info() |
|
316 | _, exc_value, _ = sys.exc_info() | |
317 | return exc_value |
|
317 | return exc_value | |
318 | else: |
|
318 | else: | |
319 | return "ERROR:: No file(s) found to upload" |
|
319 | return "ERROR:: No file(s) found to upload" | |
320 |
|
320 | |||
321 | def upload_multiple_files(self, dataset_id, path_files, date_files, type_files, ignore_repetition=False, **kwargs): |
|
321 | def upload_multiple_files(self, dataset_id, path_files, date_files, type_files, ignore_repetition=False, **kwargs): | |
322 | # Agregar si es interruptido por teclado |
|
322 | # Agregar si es interruptido por teclado | |
323 | ''' |
|
323 | ''' | |
324 | FINALIDAD: |
|
324 | FINALIDAD: | |
325 | Funcion para subir multiples archivos al repositorio del ROJ. |
|
325 | Funcion para subir multiples archivos al repositorio del ROJ. | |
326 |
|
326 | |||
327 | PARAMETROS DISPONIBLES: |
|
327 | PARAMETROS DISPONIBLES: | |
328 | CONSULTAR: "GUIA DE SCRIPT.pdf" |
|
328 | CONSULTAR: "GUIA DE SCRIPT.pdf" | |
329 |
|
329 | |||
330 | ESTRUCTURA: |
|
330 | ESTRUCTURA: | |
331 | <access_name>.upload_multiple_files(dataset_id = <class 'str'>, path_files = <class 'str'> or <class 'list of strings'>, date_files = <class 'str'> or <class 'list of strings'>, type_files = <class 'str'> or <class 'list of strings'>, param_1 = <class 'param_1'>, ...) |
|
331 | <access_name>.upload_multiple_files(dataset_id = <class 'str'>, path_files = <class 'str'> or <class 'list of strings'>, date_files = <class 'str'> or <class 'list of strings'>, type_files = <class 'str'> or <class 'list of strings'>, param_1 = <class 'param_1'>, ...) | |
332 | ''' |
|
332 | ''' | |
333 | #-------------------------PACKAGE SHOW-----------------------# |
|
333 | #-------------------------PACKAGE SHOW-----------------------# | |
334 | try: |
|
334 | try: | |
335 | dataset_show = getattr(self.ckan.action, 'package_show')(id=dataset_id)['resources'] |
|
335 | dataset_show = getattr(self.ckan.action, 'package_show')(id=dataset_id)['resources'] | |
336 | except: |
|
336 | except: | |
337 | _, exc_value, _ = sys.exc_info() |
|
337 | _, exc_value, _ = sys.exc_info() | |
338 | print('ERROR obtaining metadata dataset:: Use the "print" for more information') |
|
338 | print('ERROR obtaining metadata dataset:: Use the "print" for more information') | |
339 | return exc_value |
|
339 | return exc_value | |
340 | #------------------------------------------------------------# |
|
340 | #------------------------------------------------------------# | |
341 | resources_name = [] |
|
341 | resources_name = [] | |
342 | for u in dataset_show: |
|
342 | for u in dataset_show: | |
343 | resources_name.append(u['name'].lower()) |
|
343 | resources_name.append(u['name'].lower()) | |
344 | #------------------------------------------------------------# |
|
344 | #------------------------------------------------------------# | |
345 |
|
345 | |||
346 | params_dict = {'upload':[], 'name':[]} |
|
346 | params_dict = {'upload':[], 'name':[]} | |
347 | #if not 'format' in kwargs: |
|
347 | #if not 'format' in kwargs: | |
348 | # params_dict.update({'format':[]}) |
|
348 | # params_dict.update({'format':[]}) | |
349 | #---------------CASO : "path" or "path_list"-----------------# |
|
349 | #---------------CASO : "path" or "path_list"-----------------# | |
350 | if type(path_files) is list: |
|
350 | if type(path_files) is list: | |
351 | if len(path_files) != 0: |
|
351 | if len(path_files) != 0: | |
352 | path_files.sort() |
|
352 | path_files.sort() | |
353 | for u in path_files: |
|
353 | for u in path_files: | |
354 | if os.path.isfile(u): |
|
354 | if os.path.isfile(u): | |
355 | if os.path.basename(u).lower() in resources_name: |
|
355 | if os.path.basename(u).lower() in resources_name: | |
356 | if not ignore_repetition: |
|
356 | if not ignore_repetition: | |
357 | return 'ERROR:: "%s" file already exist in this dataset' % (os.path.basename(u)) |
|
357 | return 'ERROR:: "%s" file already exist in this dataset' % (os.path.basename(u)) | |
358 | print('WARRING:: "'+ str(os.path.basename(u)) +'" file was ignored because already exist in this dataset') |
|
358 | print('WARRING:: "'+ str(os.path.basename(u)) +'" file was ignored because already exist in this dataset') | |
359 | else: |
|
359 | else: | |
360 | params_dict['upload'].append(open(u, 'rb')) |
|
360 | params_dict['upload'].append(open(u, 'rb')) | |
361 | params_dict['name'].append(os.path.basename(u)) |
|
361 | params_dict['name'].append(os.path.basename(u)) | |
362 | #if not 'format' in kwargs: |
|
362 | #if not 'format' in kwargs: | |
363 | # format = ''.join(pathlib.Path(u).suffixes) |
|
363 | # format = ''.join(pathlib.Path(u).suffixes) | |
364 | # if len(format) > 0: |
|
364 | # if len(format) > 0: | |
365 | # params_dict['format'].append(format.upper()[1:]) |
|
365 | # params_dict['format'].append(format.upper()[1:]) | |
366 | # else: |
|
366 | # else: | |
367 | # params_dict['format'].append('') |
|
367 | # params_dict['format'].append('') | |
368 | else: |
|
368 | else: | |
369 | return 'File "%s" does not exist' % (u) |
|
369 | return 'File "%s" does not exist' % (u) | |
370 | else: |
|
370 | else: | |
371 | return 'ERROR:: "path_list is empty"' |
|
371 | return 'ERROR:: "path_list is empty"' | |
372 | elif type(path_files) is str: |
|
372 | elif type(path_files) is str: | |
373 | if os.path.isdir(path_files): |
|
373 | if os.path.isdir(path_files): | |
374 | path_order = [f for f in os.listdir(path_files) if os.path.isfile(os.path.join(path_files, f))] |
|
374 | path_order = [f for f in os.listdir(path_files) if os.path.isfile(os.path.join(path_files, f))] | |
375 | path_order.sort() |
|
375 | path_order.sort() | |
376 | if path_order: |
|
376 | if path_order: | |
377 | for name in path_order: |
|
377 | for name in path_order: | |
378 | if name.lower() in resources_name: |
|
378 | if name.lower() in resources_name: | |
379 | if not ignore_repetition: |
|
379 | if not ignore_repetition: | |
380 | return 'ERROR:: "%s" file already exist in this dataset' % (name) |
|
380 | return 'ERROR:: "%s" file already exist in this dataset' % (name) | |
381 | print('WARRING:: "'+ str(name) +'" file was ignored because already exist in this dataset') |
|
381 | print('WARRING:: "'+ str(name) +'" file was ignored because already exist in this dataset') | |
382 | else: |
|
382 | else: | |
383 | params_dict['upload'].append(open(os.path.join(path_files, name), 'rb')) |
|
383 | params_dict['upload'].append(open(os.path.join(path_files, name), 'rb')) | |
384 | params_dict['name'].append(name) |
|
384 | params_dict['name'].append(name) | |
385 | #if not 'format' in kwargs: |
|
385 | #if not 'format' in kwargs: | |
386 | # format = ''.join(pathlib.Path(name).suffixes) |
|
386 | # format = ''.join(pathlib.Path(name).suffixes) | |
387 | # if len(format) > 0: |
|
387 | # if len(format) > 0: | |
388 | # params_dict['format'].append(format.upper()[1:]) |
|
388 | # params_dict['format'].append(format.upper()[1:]) | |
389 | # else: |
|
389 | # else: | |
390 | # params_dict['format'].append('') |
|
390 | # params_dict['format'].append('') | |
391 | else: |
|
391 | else: | |
392 | return "ERROR:: There aren't files in this directory" |
|
392 | return "ERROR:: There aren't files in this directory" | |
393 | else: |
|
393 | else: | |
394 | return 'ERROR:: Directory "%s" does not exist' % (path_files) |
|
394 | return 'ERROR:: Directory "%s" does not exist' % (path_files) | |
395 | else: |
|
395 | else: | |
396 | return 'ERROR:: "path_files" must be a str or list' |
|
396 | return 'ERROR:: "path_files" must be a str or list' | |
397 | #------------------------------------------------------------# |
|
397 | #------------------------------------------------------------# | |
398 | params_no_dict = {'package_id': dataset_id} |
|
398 | params_no_dict = {'package_id': dataset_id} | |
399 | if type(date_files) is list: |
|
399 | if type(date_files) is list: | |
400 | params_dict['file_date'] = date_files |
|
400 | params_dict['file_date'] = date_files | |
401 | else: |
|
401 | else: | |
402 | params_no_dict['file_date'] = date_files |
|
402 | params_no_dict['file_date'] = date_files | |
403 |
|
403 | |||
404 | if type(type_files) is list: |
|
404 | if type(type_files) is list: | |
405 | params_dict['voc_file_type'] = type_files |
|
405 | params_dict['voc_file_type'] = type_files | |
406 | else: |
|
406 | else: | |
407 | params_no_dict['voc_file_type'] = type_files |
|
407 | params_no_dict['voc_file_type'] = type_files | |
408 |
|
408 | |||
409 | for key1, value1 in kwargs.items(): |
|
409 | for key1, value1 in kwargs.items(): | |
410 | if not key1 in params_dict and not key1 in params_no_dict and key1 != 'others': |
|
410 | if not key1 in params_dict and not key1 in params_no_dict and key1 != 'others': | |
411 | if type(value1) is list: |
|
411 | if type(value1) is list: | |
412 | params_dict[key1] = value1 |
|
412 | params_dict[key1] = value1 | |
413 | else: |
|
413 | else: | |
414 | params_no_dict[key1] = value1 |
|
414 | params_no_dict[key1] = value1 | |
415 | #------------------------------------------# |
|
415 | #------------------------------------------# | |
416 | if not 'others' in kwargs: |
|
416 | if not 'others' in kwargs: | |
417 | params_no_dict['others'] = '' |
|
417 | params_no_dict['others'] = '' | |
418 | else: |
|
418 | else: | |
419 | if isinstance(kwargs['others'], tuple): |
|
419 | if isinstance(kwargs['others'], tuple): | |
420 | params_dict['others'] = [json.dumps(w) for w in kwargs['others']] |
|
420 | params_dict['others'] = [json.dumps(w) for w in kwargs['others']] | |
421 | elif isinstance(kwargs['others'], list): |
|
421 | elif isinstance(kwargs['others'], list): | |
422 | params_no_dict['others'] = json.dumps(kwargs['others']) |
|
422 | params_no_dict['others'] = json.dumps(kwargs['others']) | |
423 | elif isinstance(kwargs['others'], str): |
|
423 | elif isinstance(kwargs['others'], str): | |
424 | params_no_dict['others'] = kwargs['others'] |
|
424 | params_no_dict['others'] = kwargs['others'] | |
425 | else: |
|
425 | else: | |
426 | return 'ERROR:: "others" must be a tuple, list or str' |
|
426 | return 'ERROR:: "others" must be a tuple, list or str' | |
427 | #------------------------------------------# |
|
427 | #------------------------------------------# | |
428 | len_params_dict = [] |
|
428 | len_params_dict = [] | |
429 | for value2 in params_dict.values(): |
|
429 | for value2 in params_dict.values(): | |
430 | len_params_dict.append(len(value2)) |
|
430 | len_params_dict.append(len(value2)) | |
431 |
|
431 | |||
432 | if len(list(set(len_params_dict))) > 1: |
|
432 | if len(list(set(len_params_dict))) > 1: | |
433 | return 'ERROR:: All lists must be the same length: %s' % (len(params_dict['name'])) |
|
433 | return 'ERROR:: All lists must be the same length: %s' % (len(params_dict['name'])) | |
434 | #------------------------------------------------------------# |
|
434 | #------------------------------------------------------------# | |
435 | print('"{}" file(s) found >> uploading'.format(len(params_dict['name']))) |
|
435 | print('"{}" file(s) found >> uploading'.format(len(params_dict['name']))) | |
436 | for v in range(len(params_dict['name'])): |
|
436 | for v in range(len(params_dict['name'])): | |
437 | try: |
|
437 | try: | |
438 | send = {} |
|
438 | send = {} | |
439 | for key_dict, value_dict in params_dict.items(): |
|
439 | for key_dict, value_dict in params_dict.items(): | |
440 | send[key_dict] = value_dict[v] |
|
440 | send[key_dict] = value_dict[v] | |
441 | for key_no_dict, value_no_dict in params_no_dict.items(): |
|
441 | for key_no_dict, value_no_dict in params_no_dict.items(): | |
442 | send[key_no_dict] = value_no_dict |
|
442 | send[key_no_dict] = value_no_dict | |
443 |
|
443 | |||
444 | self.list.append(getattr(self.ckan.action, 'resource_create')(**send)) |
|
444 | self.list.append(getattr(self.ckan.action, 'resource_create')(**send)) | |
445 | print('File #{} :: "{}" was uploaded successfully'.format(v+1, params_dict['name'][v])) |
|
445 | print('File #{} :: "{}" was uploaded successfully'.format(v+1, params_dict['name'][v])) | |
446 | except: |
|
446 | except: | |
447 | _, exc_value, _ = sys.exc_info() |
|
447 | _, exc_value, _ = sys.exc_info() | |
448 | self.list.append(exc_value) |
|
448 | self.list.append(exc_value) | |
449 | print('File #{} :: Error uploading "{}" file'.format(v+1, params_dict['name'][v])) |
|
449 | print('File #{} :: Error uploading "{}" file'.format(v+1, params_dict['name'][v])) | |
450 | return self.list |
|
450 | return self.list | |
451 | #------------------------------------------------------------# |
|
451 | #------------------------------------------------------------# | |
452 |
|
452 | |||
453 | def show(self, type_option, id, **kwargs): |
|
453 | def show(self, type_option, id, **kwargs): | |
454 | ''' |
|
454 | ''' | |
455 | FINALIDAD: |
|
455 | FINALIDAD: | |
456 | Funcion personalizada para una busqueda en especifico. |
|
456 | Funcion personalizada para una busqueda en especifico. | |
457 |
|
457 | |||
458 | PARAMETROS DISPONIBLES: |
|
458 | PARAMETROS DISPONIBLES: | |
459 | CONSULTAR: "GUIA DE SCRIPT.pdf" |
|
459 | CONSULTAR: "GUIA DE SCRIPT.pdf" | |
460 |
|
460 | |||
461 | ESTRUCTURA: |
|
461 | ESTRUCTURA: | |
462 | <access_name>.show(type_option = <class 'str'>, id = <class 'str'>, param_1 = <class 'param_1'>, ...) |
|
462 | <access_name>.show(type_option = <class 'str'>, id = <class 'str'>, param_1 = <class 'param_1'>, ...) | |
463 | ''' |
|
463 | ''' | |
464 | if type(type_option) is str: |
|
464 | if type(type_option) is str: | |
465 | try: |
|
465 | try: | |
466 | if type_option == 'dataset': |
|
466 | if type_option == 'dataset': | |
467 | return getattr(self.ckan.action, 'package_show')(id=id, **kwargs) |
|
467 | return getattr(self.ckan.action, 'package_show')(id=id, **kwargs) | |
468 | elif type_option == 'resource': |
|
468 | elif type_option == 'resource': | |
469 | return getattr(self.ckan.action, 'resource_show')(id=id, **kwargs) |
|
469 | return getattr(self.ckan.action, 'resource_show')(id=id, **kwargs) | |
470 | elif type_option == 'project': |
|
470 | elif type_option == 'project': | |
471 | return getattr(self.ckan.action, 'organization_show')(id=id, **kwargs) |
|
471 | return getattr(self.ckan.action, 'organization_show')(id=id, **kwargs) | |
472 | elif type_option == 'collaborator': |
|
472 | elif type_option == 'collaborator': | |
473 | return getattr(self.ckan.action, 'package_collaborator_list_for_user')(id=id, **kwargs) |
|
473 | return getattr(self.ckan.action, 'package_collaborator_list_for_user')(id=id, **kwargs) | |
474 | elif type_option == 'member': |
|
474 | elif type_option == 'member': | |
475 | return getattr(self.ckan.action, 'organization_list_for_user')(id=id, **kwargs) |
|
475 | return getattr(self.ckan.action, 'organization_list_for_user')(id=id, **kwargs) | |
476 | elif type_option == 'vocabulary': |
|
476 | elif type_option == 'vocabulary': | |
477 | return getattr(self.ckan.action, 'vocabulary_show')(id=id, **kwargs) |
|
477 | return getattr(self.ckan.action, 'vocabulary_show')(id=id, **kwargs) | |
478 | elif type_option == 'tag': |
|
478 | elif type_option == 'tag': | |
479 | if not 'vocabulary_id' in kwargs: |
|
479 | if not 'vocabulary_id' in kwargs: | |
480 | print('Missing "vocabulary_id" value: assume it is a free tag') |
|
480 | print('Missing "vocabulary_id" value: assume it is a free tag') | |
481 | return getattr(self.ckan.action, 'tag_show')(id=id, **kwargs) |
|
481 | return getattr(self.ckan.action, 'tag_show')(id=id, **kwargs) | |
482 | elif type_option == 'user': |
|
482 | elif type_option == 'user': | |
483 | return getattr(self.ckan.action, 'user_show')(id=id, **kwargs) |
|
483 | return getattr(self.ckan.action, 'user_show')(id=id, **kwargs) | |
484 | elif type_option == 'job': |
|
484 | elif type_option == 'job': | |
485 | return getattr(self.ckan.action, 'job_show')(id=id, **kwargs) |
|
485 | return getattr(self.ckan.action, 'job_show')(id=id, **kwargs) | |
486 | else: |
|
486 | else: | |
487 | return 'ERROR:: "type_option = %s" is not accepted' % (type_option) |
|
487 | return 'ERROR:: "type_option = %s" is not accepted' % (type_option) | |
488 | except: |
|
488 | except: | |
489 | _, exc_value, _ = sys.exc_info() |
|
489 | _, exc_value, _ = sys.exc_info() | |
490 | return exc_value |
|
490 | return exc_value | |
491 | else: |
|
491 | else: | |
492 | return 'ERROR:: "type_option" must be a str' |
|
492 | return 'ERROR:: "type_option" must be a str' | |
493 |
|
493 | |||
494 | def search(self, type_option, query=None, **kwargs): |
|
494 | def search(self, type_option, query=None, **kwargs): | |
495 | ''' |
|
495 | ''' | |
496 | FINALIDAD: |
|
496 | FINALIDAD: | |
497 | Funcion personalizada para busquedas que satisfagan algun criterio. |
|
497 | Funcion personalizada para busquedas que satisfagan algun criterio. | |
498 |
|
498 | |||
499 | PARAMETROS DISPONIBLES: |
|
499 | PARAMETROS DISPONIBLES: | |
500 | CONSULTAR: "GUIA DE SCRIPT.pdf" |
|
500 | CONSULTAR: "GUIA DE SCRIPT.pdf" | |
501 |
|
501 | |||
502 | ESTRUCTURA: |
|
502 | ESTRUCTURA: | |
503 | <access_name>.search(type_option = <class 'str'>, query = <class 'dict'>, param_1 = <class 'param_1'>, ...) |
|
503 | <access_name>.search(type_option = <class 'str'>, query = <class 'dict'>, param_1 = <class 'param_1'>, ...) | |
504 | ''' |
|
504 | ''' | |
505 | if type(type_option) is str: |
|
505 | if type(type_option) is str: | |
506 | try: |
|
506 | try: | |
507 | if type_option == 'dataset': |
|
507 | if type_option == 'dataset': | |
508 | key_replace = ['fq', 'fq_list', 'include_private'] |
|
508 | key_replace = ['fq', 'fq_list', 'include_private'] | |
509 | key_point = ['facet_mincount', 'facet_limit', 'facet_field'] |
|
509 | key_point = ['facet_mincount', 'facet_limit', 'facet_field'] | |
510 | for key1, value1 in kwargs.items(): |
|
510 | for key1, value1 in kwargs.items(): | |
511 | if not key1 in key_replace: |
|
511 | if not key1 in key_replace: | |
512 | if key1 in key_point: |
|
512 | if key1 in key_point: | |
513 | self.dict[key1.replace('_', '.')] = value1 |
|
513 | self.dict[key1.replace('_', '.')] = value1 | |
514 | else: |
|
514 | else: | |
515 | self.dict[key1] = value1 |
|
515 | self.dict[key1] = value1 | |
516 |
|
516 | |||
517 | if query is not None: |
|
517 | if query is not None: | |
518 | if type(query) is dict: |
|
518 | if type(query) is dict: | |
519 | self.dict['fq_list'] = [] |
|
519 | self.dict['fq_list'] = [] | |
520 | #NUM_RESOURCES_MIN / NUM_RESOURCES_MAX |
|
520 | #NUM_RESOURCES_MIN / NUM_RESOURCES_MAX | |
521 | #----------------------------------------------------# |
|
521 | #----------------------------------------------------# | |
522 | if 'dataset_start_date' in query: |
|
522 | if 'dataset_start_date' in query: | |
523 | if type(query['dataset_start_date']) is str: |
|
523 | if type(query['dataset_start_date']) is str: | |
524 | try: |
|
524 | try: | |
525 | datetime.strptime(query['dataset_start_date'], '%Y-%m-%d') |
|
525 | datetime.strptime(query['dataset_start_date'], '%Y-%m-%d') | |
526 | if len(query['dataset_start_date']) != 10: |
|
526 | if len(query['dataset_start_date']) != 10: | |
527 | return '"dataset_start_date", must be: <YYYY-MM-DD>' |
|
527 | return '"dataset_start_date", must be: <YYYY-MM-DD>' | |
528 | self.dict['fq_list'].append('dataset_start_date:"'+query['dataset_start_date']+'"') |
|
528 | self.dict['fq_list'].append('dataset_start_date:"'+query['dataset_start_date']+'"') | |
529 | self.list.append('dataset_start_date') |
|
529 | self.list.append('dataset_start_date') | |
530 | except: |
|
530 | except: | |
531 | return '"dataset_start_date" incorrect: "%s"' % (query['dataset_start_date']) |
|
531 | return '"dataset_start_date" incorrect: "%s"' % (query['dataset_start_date']) | |
532 | else: |
|
532 | else: | |
533 | return '"dataset_start_date" must be <str>' |
|
533 | return '"dataset_start_date" must be <str>' | |
534 | #----------------------------------------------------# |
|
534 | #----------------------------------------------------# | |
535 | if 'dataset_end_date' in query: |
|
535 | if 'dataset_end_date' in query: | |
536 | if type(query['dataset_end_date']) is str: |
|
536 | if type(query['dataset_end_date']) is str: | |
537 | try: |
|
537 | try: | |
538 | datetime.strptime(query['dataset_end_date'], '%Y-%m-%d') |
|
538 | datetime.strptime(query['dataset_end_date'], '%Y-%m-%d') | |
539 | if len(query['dataset_end_date']) != 10: |
|
539 | if len(query['dataset_end_date']) != 10: | |
540 | return '"dataset_end_date", must be: <YYYY-MM-DD>' |
|
540 | return '"dataset_end_date", must be: <YYYY-MM-DD>' | |
541 |
|
541 | |||
542 | if 'dataset_start_date' in query: |
|
542 | if 'dataset_start_date' in query: | |
543 | if query['dataset_start_date'] > query['dataset_end_date']: |
|
543 | if query['dataset_start_date'] > query['dataset_end_date']: | |
544 | return '"dataset_end_date" must be greater than "dataset_start_date"' |
|
544 | return '"dataset_end_date" must be greater than "dataset_start_date"' | |
545 |
|
545 | |||
546 | self.dict['fq_list'].append('dataset_end_date:"'+query['dataset_end_date']+'"') |
|
546 | self.dict['fq_list'].append('dataset_end_date:"'+query['dataset_end_date']+'"') | |
547 | self.list.append('dataset_end_date') |
|
547 | self.list.append('dataset_end_date') | |
548 | except: |
|
548 | except: | |
549 | return '"dataset_end_date" incorrect: "%s"' % (query['dataset_end_date']) |
|
549 | return '"dataset_end_date" incorrect: "%s"' % (query['dataset_end_date']) | |
550 | else: |
|
550 | else: | |
551 | return '"dataset_end_date" must be <str>' |
|
551 | return '"dataset_end_date" must be <str>' | |
552 | #----------------------------------------------------# |
|
552 | #----------------------------------------------------# | |
553 | for key, value in query.items(): |
|
553 | for key, value in query.items(): | |
554 | if value is not None and not key in self.list: |
|
554 | if value is not None and not key in self.list: | |
555 | self.dict['fq_list'].append(str(key)+':"'+str(value)+'"') |
|
555 | self.dict['fq_list'].append(str(key)+':"'+str(value)+'"') | |
556 | else: |
|
556 | else: | |
557 | return '"query" must be <dict>' |
|
557 | return '"query" must be <dict>' | |
558 |
|
558 | |||
559 | return getattr(self.ckan.action, 'package_search')(include_private=True, **self.dict) |
|
559 | return getattr(self.ckan.action, 'package_search')(include_private=True, **self.dict) | |
560 |
|
560 | |||
561 | elif type_option == 'resource': |
|
561 | elif type_option == 'resource': | |
562 | for key1, value1 in kwargs.items(): |
|
562 | for key1, value1 in kwargs.items(): | |
563 | if key1 != 'fields': |
|
563 | if key1 != 'fields': | |
564 | self.dict[key1] = value1 |
|
564 | self.dict[key1] = value1 | |
565 |
|
565 | |||
566 | if query is not None: |
|
566 | if query is not None: | |
567 | if type(query) is dict: |
|
567 | if type(query) is dict: | |
568 | #----------------------------------------------------# |
|
568 | #----------------------------------------------------# | |
569 | if 'file_date_min' in query: |
|
569 | if 'file_date_min' in query: | |
570 | if type(query['file_date_min']) is str: |
|
570 | if type(query['file_date_min']) is str: | |
571 | try: |
|
571 | try: | |
572 | datetime.strptime(query['file_date_min'], '%Y-%m-%d') |
|
572 | datetime.strptime(query['file_date_min'], '%Y-%m-%d') | |
573 | if len(query['file_date_min']) != 10: |
|
573 | if len(query['file_date_min']) != 10: | |
574 | return '"file_date_min", must be: <YYYY-MM-DD>' |
|
574 | return '"file_date_min", must be: <YYYY-MM-DD>' | |
575 | except: |
|
575 | except: | |
576 | return '"file_date_min" incorrect: "%s"' % (query['file_date_min']) |
|
576 | return '"file_date_min" incorrect: "%s"' % (query['file_date_min']) | |
577 | else: |
|
577 | else: | |
578 | return '"file_date_min" must be <str>' |
|
578 | return '"file_date_min" must be <str>' | |
579 | #----------------------------------------------------# |
|
579 | #----------------------------------------------------# | |
580 | if 'file_date_max' in query: |
|
580 | if 'file_date_max' in query: | |
581 | if type(query['file_date_max']) is str: |
|
581 | if type(query['file_date_max']) is str: | |
582 | try: |
|
582 | try: | |
583 | datetime.strptime(query['file_date_max'], '%Y-%m-%d') |
|
583 | datetime.strptime(query['file_date_max'], '%Y-%m-%d') | |
584 | if len(query['file_date_max']) != 10: |
|
584 | if len(query['file_date_max']) != 10: | |
585 | return '"file_date_max", must be: <YYYY-MM-DD>' |
|
585 | return '"file_date_max", must be: <YYYY-MM-DD>' | |
586 |
|
586 | |||
587 | if 'file_date_min' in query: |
|
587 | if 'file_date_min' in query: | |
588 | if query['file_date_min'] > query['file_date_max']: |
|
588 | if query['file_date_min'] > query['file_date_max']: | |
589 | return '"file_date_max" must be greater than "file_date_min"' |
|
589 | return '"file_date_max" must be greater than "file_date_min"' | |
590 | except: |
|
590 | except: | |
591 | return '"file_date_max" incorrect: "%s"' % (query['file_date_max']) |
|
591 | return '"file_date_max" incorrect: "%s"' % (query['file_date_max']) | |
592 | else: |
|
592 | else: | |
593 | return '"file_date_max" must be <str>' |
|
593 | return '"file_date_max" must be <str>' | |
594 | #----------------------------------------------------# |
|
594 | #----------------------------------------------------# | |
595 | self.dict['query'] = query |
|
595 | self.dict['query'] = query | |
596 | else: |
|
596 | else: | |
597 | return '"query" must be <dict>' |
|
597 | return '"query" must be <dict>' | |
598 | return getattr(self.ckan.action, 'resources_search')(**self.dict) |
|
598 | return getattr(self.ckan.action, 'resources_search')(**self.dict) | |
599 |
|
599 | |||
600 | elif type_option == 'tag': |
|
600 | elif type_option == 'tag': | |
601 | for key1, value1 in kwargs.items(): |
|
601 | for key1, value1 in kwargs.items(): | |
602 | if key1 != 'fields': |
|
602 | if key1 != 'fields': | |
603 | self.dict[key1] = value1 |
|
603 | self.dict[key1] = value1 | |
604 |
|
604 | |||
605 | if not 'vocabulary_id' in kwargs: |
|
605 | if not 'vocabulary_id' in kwargs: | |
606 | print('Missing "vocabulary_id" value: tags that don’t belong to any vocabulary') |
|
606 | print('Missing "vocabulary_id" value: tags that don’t belong to any vocabulary') | |
607 | else: |
|
607 | else: | |
608 | print('Only tags that belong to "{}" vocabulary'.format(kwargs['vocabulary_id'])) |
|
608 | print('Only tags that belong to "{}" vocabulary'.format(kwargs['vocabulary_id'])) | |
609 |
|
609 | |||
610 | if query is not None: |
|
610 | if query is not None: | |
611 | if type(query) is dict: |
|
611 | if type(query) is dict: | |
612 | if 'search' in query: |
|
612 | if 'search' in query: | |
613 | if type(query['search']) is list or type(query['search']) is str: |
|
613 | if type(query['search']) is list or type(query['search']) is str: | |
614 | self.dict['query'] = query['search'] |
|
614 | self.dict['query'] = query['search'] | |
615 | else: |
|
615 | else: | |
616 | return '"search" must be <list> or <str>' |
|
616 | return '"search" must be <list> or <str>' | |
617 | else: |
|
617 | else: | |
618 | return '"query" must be <dict>' |
|
618 | return '"query" must be <dict>' | |
619 | return getattr(self.ckan.action, 'tag_search')(**self.dict) |
|
619 | return getattr(self.ckan.action, 'tag_search')(**self.dict) | |
620 |
|
620 | |||
621 | else: |
|
621 | else: | |
622 | return 'ERROR:: "type_option = %s" is not accepted' % (type_option) |
|
622 | return 'ERROR:: "type_option = %s" is not accepted' % (type_option) | |
623 |
|
623 | |||
624 | except: |
|
624 | except: | |
625 | _, exc_value, _ = sys.exc_info() |
|
625 | _, exc_value, _ = sys.exc_info() | |
626 | return exc_value |
|
626 | return exc_value | |
627 | else: |
|
627 | else: | |
628 | return 'ERROR:: "type_option" must be <str>' |
|
628 | return 'ERROR:: "type_option" must be <str>' | |
629 |
|
629 | |||
630 | def create(self, type_option, select=None, **kwargs): |
|
630 | def create(self, type_option, select=None, **kwargs): | |
631 | ''' |
|
631 | ''' | |
632 | FINALIDAD: |
|
632 | FINALIDAD: | |
633 | Funcion personalizada para crear. |
|
633 | Funcion personalizada para crear. | |
634 |
|
634 | |||
635 | PARAMETROS DISPONIBLES: |
|
635 | PARAMETROS DISPONIBLES: | |
636 | CONSULTAR: "GUIA DE SCRIPT.pdf" |
|
636 | CONSULTAR: "GUIA DE SCRIPT.pdf" | |
637 |
|
637 | |||
638 | ESTRUCTURA: |
|
638 | ESTRUCTURA: | |
639 | <access_name>.create(type_option = <class 'str'>, param_1 = <class 'param_1'>, ...) |
|
639 | <access_name>.create(type_option = <class 'str'>, param_1 = <class 'param_1'>, ...) | |
640 | ''' |
|
640 | ''' | |
641 | if type(type_option) is str: |
|
641 | if type(type_option) is str: | |
642 | try: |
|
642 | try: | |
643 | if type_option == 'dataset': |
|
643 | if type_option == 'dataset': | |
644 | return getattr(self.ckan.action, 'package_create')(**kwargs) |
|
644 | return getattr(self.ckan.action, 'package_create')(**kwargs) | |
645 | elif type_option == 'project': |
|
645 | elif type_option == 'project': | |
646 | return getattr(self.ckan.action, 'organization_create')(**kwargs) |
|
646 | return getattr(self.ckan.action, 'organization_create')(**kwargs) | |
647 | elif type_option == 'member': |
|
647 | elif type_option == 'member': | |
648 | return getattr(self.ckan.action, 'organization_member_create')(**kwargs) |
|
648 | return getattr(self.ckan.action, 'organization_member_create')(**kwargs) | |
649 | elif type_option == 'collaborator': |
|
649 | elif type_option == 'collaborator': | |
650 | return getattr(self.ckan.action, 'package_collaborator_create')(**kwargs) |
|
650 | return getattr(self.ckan.action, 'package_collaborator_create')(**kwargs) | |
651 | elif type_option == 'vocabulary': |
|
651 | elif type_option == 'vocabulary': | |
652 | return getattr(self.ckan.action, 'vocabulary_create')(**kwargs) |
|
652 | return getattr(self.ckan.action, 'vocabulary_create')(**kwargs) | |
653 | elif type_option == 'tag': |
|
653 | elif type_option == 'tag': | |
654 | return getattr(self.ckan.action, 'tag_create')(**kwargs) |
|
654 | return getattr(self.ckan.action, 'tag_create')(**kwargs) | |
655 | elif type_option == 'user': |
|
655 | elif type_option == 'user': | |
656 | return getattr(self.ckan.action, 'user_create')(**kwargs) |
|
656 | return getattr(self.ckan.action, 'user_create')(**kwargs) | |
657 | elif type_option == 'views': |
|
657 | elif type_option == 'views': | |
658 | if 'resource' == select: |
|
658 | if 'resource' == select: | |
659 | self.list = ['package'] |
|
659 | self.list = ['package'] | |
660 | for key1, value1 in kwargs.items(): |
|
660 | for key1, value1 in kwargs.items(): | |
661 | if not key1 in self.list: |
|
661 | if not key1 in self.list: | |
662 | self.dict[key1] = value1 |
|
662 | self.dict[key1] = value1 | |
663 | return getattr(self.ckan.action, 'resource_create_default_resource_views')(**self.dict) |
|
663 | return getattr(self.ckan.action, 'resource_create_default_resource_views')(**self.dict) | |
664 | elif 'dataset' == select: |
|
664 | elif 'dataset' == select: | |
665 | return getattr(self.ckan.action, 'package_create_default_resource_views')(**kwargs) |
|
665 | return getattr(self.ckan.action, 'package_create_default_resource_views')(**kwargs) | |
666 | else: |
|
666 | else: | |
667 | return 'ERROR:: "select = %s" is not accepted' % (select) |
|
667 | return 'ERROR:: "select = %s" is not accepted' % (select) | |
668 | else: |
|
668 | else: | |
669 | return 'ERROR:: "type_option = %s" is not accepted' % (type_option) |
|
669 | return 'ERROR:: "type_option = %s" is not accepted' % (type_option) | |
670 | except: |
|
670 | except: | |
671 | _, exc_value, _ = sys.exc_info() |
|
671 | _, exc_value, _ = sys.exc_info() | |
672 | return exc_value |
|
672 | return exc_value | |
673 | else: |
|
673 | else: | |
674 | return 'ERROR:: "type_option" must be <str>' |
|
674 | return 'ERROR:: "type_option" must be <str>' | |
675 |
|
675 | |||
676 | def patch(self, type_option, **kwargs): |
|
676 | def patch(self, type_option, **kwargs): | |
677 | ''' |
|
677 | ''' | |
678 | FINALIDAD: |
|
678 | FINALIDAD: | |
679 | Funciones personalizadas para actualizar |
|
679 | Funciones personalizadas para actualizar | |
680 |
|
680 | |||
681 | PARAMETROS DISPONIBLES: |
|
681 | PARAMETROS DISPONIBLES: | |
682 | CONSULTAR: "GUIA DE SCRIPT.pdf" |
|
682 | CONSULTAR: "GUIA DE SCRIPT.pdf" | |
683 |
|
683 | |||
684 | ESTRUCTURA: |
|
684 | ESTRUCTURA: | |
685 | <access_name>.patch(type_option = <class 'str'>, param_1 = <class 'param_1'>, ...) |
|
685 | <access_name>.patch(type_option = <class 'str'>, param_1 = <class 'param_1'>, ...) | |
686 | ''' |
|
686 | ''' | |
687 | if type(type_option) is str: |
|
687 | if type(type_option) is str: | |
688 | try: |
|
688 | try: | |
689 | if type_option == 'dataset': |
|
689 | if type_option == 'dataset': | |
690 | return getattr(self.ckan.action, 'package_patch')(**kwargs) |
|
690 | return getattr(self.ckan.action, 'package_patch')(**kwargs) | |
691 | elif type_option == 'project': |
|
691 | elif type_option == 'project': | |
692 | return getattr(self.ckan.action, 'organization_patch')(**kwargs) |
|
692 | return getattr(self.ckan.action, 'organization_patch')(**kwargs) | |
693 | elif type_option == 'resource': |
|
693 | elif type_option == 'resource': | |
694 | return getattr(self.ckan.action, 'resource_patch')(**kwargs) |
|
694 | return getattr(self.ckan.action, 'resource_patch')(**kwargs) | |
695 | elif type_option == 'member': |
|
695 | elif type_option == 'member': | |
696 | return getattr(self.ckan.action, 'organization_member_create')(**kwargs) |
|
696 | return getattr(self.ckan.action, 'organization_member_create')(**kwargs) | |
697 | elif type_option == 'collaborator': |
|
697 | elif type_option == 'collaborator': | |
698 | return getattr(self.ckan.action, 'package_collaborator_create')(**kwargs) |
|
698 | return getattr(self.ckan.action, 'package_collaborator_create')(**kwargs) | |
699 | else: |
|
699 | else: | |
700 | return 'ERROR:: "type_option = %s" is not accepted' % (type_option) |
|
700 | return 'ERROR:: "type_option = %s" is not accepted' % (type_option) | |
701 | except: |
|
701 | except: | |
702 | _, exc_value, _ = sys.exc_info() |
|
702 | _, exc_value, _ = sys.exc_info() | |
703 | return exc_value |
|
703 | return exc_value | |
704 | else: |
|
704 | else: | |
705 | return 'ERROR:: "type_option" must be <str>' |
|
705 | return 'ERROR:: "type_option" must be <str>' | |
706 |
|
706 | |||
707 | def delete(self, type_option, select=None, **kwargs): |
|
707 | def delete(self, type_option, select=None, **kwargs): | |
708 | ''' |
|
708 | ''' | |
709 | FINALIDAD: |
|
709 | FINALIDAD: | |
710 | Función personalizada para eliminar y/o purgar. |
|
710 | Función personalizada para eliminar y/o purgar. | |
711 |
|
711 | |||
712 | PARAMETROS DISPONIBLES: |
|
712 | PARAMETROS DISPONIBLES: | |
713 | CONSULTAR: "GUIA DE SCRIPT.pdf" |
|
713 | CONSULTAR: "GUIA DE SCRIPT.pdf" | |
714 |
|
714 | |||
715 | ESTRUCTURA: |
|
715 | ESTRUCTURA: | |
716 | <access_name>.delete(type_option = <class 'str'>, param_1 = <class 'param_1'>, ...) |
|
716 | <access_name>.delete(type_option = <class 'str'>, param_1 = <class 'param_1'>, ...) | |
717 | ''' |
|
717 | ''' | |
718 | if type(type_option) is str: |
|
718 | if type(type_option) is str: | |
719 | try: |
|
719 | try: | |
720 | if type_option == 'dataset': |
|
720 | if type_option == 'dataset': | |
721 | if select is None: |
|
721 | if select is None: | |
722 | return 'ERROR:: "select" must not be "None"' |
|
722 | return 'ERROR:: "select" must not be "None"' | |
723 | else: |
|
723 | else: | |
724 | if 'delete' == select: |
|
724 | if 'delete' == select: | |
725 | return getattr(self.ckan.action, 'package_delete')(**kwargs) |
|
725 | return getattr(self.ckan.action, 'package_delete')(**kwargs) | |
726 | elif 'purge' == select: |
|
726 | elif 'purge' == select: | |
727 | return getattr(self.ckan.action, 'dataset_purge')(**kwargs) |
|
727 | return getattr(self.ckan.action, 'dataset_purge')(**kwargs) | |
728 | else: |
|
728 | else: | |
729 | return 'ERROR:: "select = %s" is not accepted' % (select) |
|
729 | return 'ERROR:: "select = %s" is not accepted' % (select) | |
730 | elif type_option == 'project': |
|
730 | elif type_option == 'project': | |
731 | if select is None: |
|
731 | if select is None: | |
732 | return 'ERROR:: "select" must not be "None"' |
|
732 | return 'ERROR:: "select" must not be "None"' | |
733 | else: |
|
733 | else: | |
734 | if 'delete' == select: |
|
734 | if 'delete' == select: | |
735 | return getattr(self.ckan.action, 'organization_delete')(**kwargs) |
|
735 | return getattr(self.ckan.action, 'organization_delete')(**kwargs) | |
736 | elif 'purge' == select: |
|
736 | elif 'purge' == select: | |
737 | return getattr(self.ckan.action, 'organization_purge')(**kwargs) |
|
737 | return getattr(self.ckan.action, 'organization_purge')(**kwargs) | |
738 | else: |
|
738 | else: | |
739 | return 'ERROR:: "select = %s" is not accepted' % (select) |
|
739 | return 'ERROR:: "select = %s" is not accepted' % (select) | |
740 | elif type_option == 'resource': |
|
740 | elif type_option == 'resource': | |
741 | return getattr(self.ckan.action, 'resource_delete')(**kwargs) |
|
741 | return getattr(self.ckan.action, 'resource_delete')(**kwargs) | |
742 | elif type_option == 'vocabulary': |
|
742 | elif type_option == 'vocabulary': | |
743 | return getattr(self.ckan.action, 'vocabulary_delete')(**kwargs) |
|
743 | return getattr(self.ckan.action, 'vocabulary_delete')(**kwargs) | |
744 | elif type_option == 'tag': |
|
744 | elif type_option == 'tag': | |
745 | return getattr(self.ckan.action, 'tag_delete')(**kwargs) |
|
745 | return getattr(self.ckan.action, 'tag_delete')(**kwargs) | |
746 | elif type_option == 'user': |
|
746 | elif type_option == 'user': | |
747 | return getattr(self.ckan.action, 'user_delete')(**kwargs) |
|
747 | return getattr(self.ckan.action, 'user_delete')(**kwargs) | |
748 | else: |
|
748 | else: | |
749 | return 'ERROR:: "type_option = %s" is not accepted' % (type_option) |
|
749 | return 'ERROR:: "type_option = %s" is not accepted' % (type_option) | |
750 | except: |
|
750 | except: | |
751 | _, exc_value, _ = sys.exc_info() |
|
751 | _, exc_value, _ = sys.exc_info() | |
752 | return exc_value |
|
752 | return exc_value | |
753 | else: |
|
753 | else: | |
754 | return 'ERROR:: "type_option" must be <str>' |
|
754 | return 'ERROR:: "type_option" must be <str>' | |
755 |
|
755 | |||
756 | def f_status_note(self, total, result, path): |
|
756 | def f_status_note(self, total, result, path): | |
757 | file_txt = open(path+'status_note.txt', 'w') |
|
757 | file_txt = open(path+'status_note.txt', 'w') | |
758 | file_txt = open(path+'status_note.txt', 'a') |
|
758 | file_txt = open(path+'status_note.txt', 'a') | |
759 |
|
759 | |||
760 | file_txt.write('DOWNLOADED FILE(S): "%s"' % (len(result['name']))) |
|
760 | file_txt.write('DOWNLOADED FILE(S): "%s"' % (len(result['name']))) | |
761 | file_txt.write(''+ os.linesep) |
|
761 | file_txt.write(''+ os.linesep) | |
762 | for u in result['name']: |
|
762 | for u in result['name']: | |
763 | file_txt.write(' - '+ u + os.linesep) |
|
763 | file_txt.write(' - '+ u + os.linesep) | |
764 | file_txt.write(''+ os.linesep) |
|
764 | file_txt.write(''+ os.linesep) | |
765 |
|
765 | |||
766 | file_txt.write('FAILED FILE(S): "%s"' % (len(total['name'])-len(result['name']))) |
|
766 | file_txt.write('FAILED FILE(S): "%s"' % (len(total['name'])-len(result['name']))) | |
767 | file_txt.write(''+ os.linesep) |
|
767 | file_txt.write(''+ os.linesep) | |
768 | if len(total['name'])-len(result['name']) != 0: |
|
768 | if len(total['name'])-len(result['name']) != 0: | |
769 | for u in total['name']: |
|
769 | for u in total['name']: | |
770 | if not u in result['name']: |
|
770 | if not u in result['name']: | |
771 | file_txt.write(' - '+ u + os.linesep) |
|
771 | file_txt.write(' - '+ u + os.linesep) | |
772 | else: |
|
772 | else: | |
773 | file_txt.write(' "None"'+ os.linesep) |
|
773 | file_txt.write(' "None"'+ os.linesep) | |
774 |
|
774 | |||
775 | def f_name(self, name_dataset, ext, tempdir): |
|
775 | def f_name(self, name_dataset, ext, tempdir): | |
776 | while self.check: |
|
776 | while self.check: | |
777 | self.str = '' |
|
777 | self.str = '' | |
778 | if self.cont == 0: |
|
778 | if self.cont == 0: | |
779 | if os.path.exists(tempdir + name_dataset + ext): |
|
779 | if os.path.exists(tempdir + name_dataset + ext): | |
780 | self.str = name_dataset+'('+str(self.cont+1)+')'+ext |
|
780 | self.str = name_dataset+'('+str(self.cont+1)+')'+ext | |
781 | else: |
|
781 | else: | |
782 | self.check = self.check * 0 |
|
782 | self.check = self.check * 0 | |
783 | self.str = name_dataset + ext |
|
783 | self.str = name_dataset + ext | |
784 | else: |
|
784 | else: | |
785 | if not os.path.exists(tempdir + name_dataset+'('+str(self.cont)+')'+ext): |
|
785 | if not os.path.exists(tempdir + name_dataset+'('+str(self.cont)+')'+ext): | |
786 | self.check = self.check * 0 |
|
786 | self.check = self.check * 0 | |
787 | self.str = name_dataset+'('+str(self.cont)+')'+ ext |
|
787 | self.str = name_dataset+'('+str(self.cont)+')'+ ext | |
788 | self.cont = self.cont+1 |
|
788 | self.cont = self.cont+1 | |
789 | return self.str |
|
789 | return self.str | |
790 |
|
790 | |||
791 | def f_zipdir(self, path, ziph, zip_name): |
|
791 | def f_zipdir(self, path, ziph, zip_name): | |
792 | for root, _, files in os.walk(path): |
|
792 | for root, _, files in os.walk(path): | |
793 | print('.....') |
|
793 | print('.....') | |
794 | print('Creating: "{}" >>'.format(zip_name)) |
|
794 | print('Creating: "{}" >>'.format(zip_name)) | |
795 | for __file in tqdm(iterable=files, total=len(files)): |
|
795 | for __file in tqdm(iterable=files, total=len(files)): | |
796 | new_dir = os.path.relpath(os.path.join(root, __file), os.path.join(path, '..')) |
|
796 | new_dir = os.path.relpath(os.path.join(root, __file), os.path.join(path, '..')) | |
797 | ziph.write(os.path.join(root, __file), new_dir) |
|
797 | ziph.write(os.path.join(root, __file), new_dir) | |
798 | print('Created >>') |
|
798 | print('Created >>') | |
799 |
|
799 | |||
800 | def download_by_step(self, response, tempdir_name): |
|
800 | def download_by_step(self, response, tempdir_name): | |
801 | try: |
|
801 | try: | |
802 | # ---------- REPLACE URL --------- # |
|
802 | # ---------- REPLACE URL --------- # | |
803 | if urlparse(self.url).netloc != 'www.igp.gob.pe' and urlparse(response['url']).netloc == 'www.igp.gob.pe': |
|
803 | if urlparse(self.url).netloc != 'www.igp.gob.pe' and urlparse(response['url']).netloc == 'www.igp.gob.pe': | |
804 | response['url'] = response['url'].replace(urlparse(response['url']).scheme + '://' + urlparse(response['url']).netloc, |
|
804 | response['url'] = response['url'].replace(urlparse(response['url']).scheme + '://' + urlparse(response['url']).netloc, | |
805 | urlparse(self.url).scheme + '://' + urlparse(self.url).netloc) |
|
805 | urlparse(self.url).scheme + '://' + urlparse(self.url).netloc) | |
806 | #----------------------------------# |
|
806 | #----------------------------------# | |
807 | with requests.get(response['url'], stream=True, headers={'Authorization': self.Authorization}, verify=self.verify) as resp: |
|
807 | with requests.get(response['url'], stream=True, headers={'Authorization': self.Authorization}, verify=self.verify) as resp: | |
808 | if resp.status_code == 200: |
|
808 | if resp.status_code == 200: | |
809 | with open(tempdir_name+response['name'], 'wb') as file: |
|
809 | with open(tempdir_name+response['name'], 'wb') as file: | |
810 | for chunk in resp.iter_content(chunk_size = self.chunk_size): |
|
810 | for chunk in resp.iter_content(chunk_size = self.chunk_size): | |
811 | if chunk: |
|
811 | if chunk: | |
812 | file.write(chunk) |
|
812 | file.write(chunk) | |
813 | except requests.exceptions.RequestException: |
|
813 | except requests.exceptions.RequestException: | |
814 | pass |
|
814 | pass | |
815 |
|
815 | |||
816 | def download_files(self, **kwargs): |
|
816 | def download_files(self, **kwargs): | |
817 | ''' |
|
817 | ''' | |
818 | FINALIDAD: |
|
818 | FINALIDAD: | |
819 | Funcion personalizada para la descarga de archivos existentes de un dataset. |
|
819 | Funcion personalizada para la descarga de archivos existentes de un dataset. | |
820 |
|
820 | |||
821 | PARAMETROS DISPONIBLES: |
|
821 | PARAMETROS DISPONIBLES: | |
822 | CONSULTAR: "GUIA DE SCRIPT.pdf" |
|
822 | CONSULTAR: "GUIA DE SCRIPT.pdf" | |
823 |
|
823 | |||
824 | ESTRUCTURA: |
|
824 | ESTRUCTURA: | |
825 | <access_name>.download_files(id = <class 'str'>, param_1 = <class 'param_1'>, ...) |
|
825 | <access_name>.download_files(id = <class 'str'>, param_1 = <class 'param_1'>, ...) | |
826 | ''' |
|
826 | ''' | |
827 | dict_local = {} |
|
827 | dict_local = {} | |
828 | #----------------------------------------------# |
|
828 | #----------------------------------------------# | |
829 | if 'zip' in kwargs: |
|
829 | if 'zip' in kwargs: | |
830 | if type(kwargs['zip']) is not bool: |
|
830 | if type(kwargs['zip']) is not bool: | |
831 | return 'ERROR:: "zip" must be: <class "bool">' |
|
831 | return 'ERROR:: "zip" must be: <class "bool">' | |
832 | else: |
|
832 | else: | |
833 | dict_local['zip'] = kwargs['zip'] |
|
833 | dict_local['zip'] = kwargs['zip'] | |
834 | else: |
|
834 | else: | |
835 | dict_local['zip'] = False |
|
835 | dict_local['zip'] = False | |
836 | #----------------------------------------------# |
|
836 | #----------------------------------------------# | |
837 | if 'status_note' in kwargs: |
|
837 | if 'status_note' in kwargs: | |
838 | if type(kwargs['status_note']) is not bool: |
|
838 | if type(kwargs['status_note']) is not bool: | |
839 | return 'ERROR:: "status_note" must be: <class "bool">' |
|
839 | return 'ERROR:: "status_note" must be: <class "bool">' | |
840 | else: |
|
840 | else: | |
841 | dict_local['status_note'] = kwargs['status_note'] |
|
841 | dict_local['status_note'] = kwargs['status_note'] | |
842 | else: |
|
842 | else: | |
843 | dict_local['status_note'] = False |
|
843 | dict_local['status_note'] = False | |
844 | #----------------------------------------------# |
|
844 | #----------------------------------------------# | |
845 | if 'path' in kwargs: |
|
845 | if 'path' in kwargs: | |
846 | if type(kwargs['path']) is str: |
|
846 | if type(kwargs['path']) is str: | |
847 | if os.path.isdir(kwargs['path']) == False: |
|
847 | if os.path.isdir(kwargs['path']) == False: | |
848 | return 'ERROR:: "path" does not exist' |
|
848 | return 'ERROR:: "path" does not exist' | |
849 | else: |
|
849 | else: | |
850 | if kwargs['path'][-1:] != self.separator: |
|
850 | if kwargs['path'][-1:] != self.separator: | |
851 | dict_local['path'] = kwargs['path']+self.separator |
|
851 | dict_local['path'] = kwargs['path']+self.separator | |
852 | else: |
|
852 | else: | |
853 | dict_local['path'] = kwargs['path'] |
|
853 | dict_local['path'] = kwargs['path'] | |
854 |
|
854 | |||
855 | txt = dict_local['path']+datetime.now().strftime("%Y_%m_%d_%H_%M_%S_%f")+'.txt' |
|
855 | txt = dict_local['path']+datetime.now().strftime("%Y_%m_%d_%H_%M_%S_%f")+'.txt' | |
856 | if int(platform.python_version()[0]) == 3: |
|
856 | if int(platform.python_version()[0]) == 3: | |
857 | try: |
|
857 | try: | |
858 | file_txt = open(txt, 'w') |
|
858 | file_txt = open(txt, 'w') | |
859 | file_txt.close() |
|
859 | file_txt.close() | |
860 | os.remove(txt) |
|
860 | os.remove(txt) | |
861 | except PermissionError: |
|
861 | except PermissionError: | |
862 | return 'ERROR:: Access denied, you are not authorized to write files: "%s"' % (dict_local['path']) |
|
862 | return 'ERROR:: Access denied, you are not authorized to write files: "%s"' % (dict_local['path']) | |
863 | else: |
|
863 | else: | |
864 | try: |
|
864 | try: | |
865 | file_txt = open(txt, 'w') |
|
865 | file_txt = open(txt, 'w') | |
866 | file_txt.close() |
|
866 | file_txt.close() | |
867 | os.remove(txt) |
|
867 | os.remove(txt) | |
868 | except: |
|
868 | except: | |
869 | return 'ERROR:: Access denied, you are not authorized to write files: "%s"' % (dict_local['path']) |
|
869 | return 'ERROR:: Access denied, you are not authorized to write files: "%s"' % (dict_local['path']) | |
870 | else: |
|
870 | else: | |
871 | return 'ERROR:: "path" must be: <class "str">' |
|
871 | return 'ERROR:: "path" must be: <class "str">' | |
872 | else: |
|
872 | else: | |
873 | dict_local['path'] = '' |
|
873 | dict_local['path'] = '' | |
874 | #----------------------------------------------# |
|
874 | #----------------------------------------------# | |
875 | for key, value in kwargs.items(): |
|
875 | for key, value in kwargs.items(): | |
876 | if not key in dict_local: |
|
876 | if not key in dict_local: | |
877 | self.dict[key] = value |
|
877 | self.dict[key] = value | |
878 | try: |
|
878 | try: | |
879 | response = getattr(self.ckan.action, 'url_resources')(**self.dict) |
|
879 | response = getattr(self.ckan.action, 'url_resources')(**self.dict) | |
880 | except: |
|
880 | except: | |
881 | _, exc_value, _ = sys.exc_info() |
|
881 | _, exc_value, _ = sys.exc_info() | |
882 | return exc_value |
|
882 | return exc_value | |
883 |
|
883 | |||
884 | if len(response) != 0: |
|
884 | if len(response) != 0: | |
885 | #--------------TEMP PATH---------------# |
|
885 | #--------------TEMP PATH---------------# | |
886 | if dict_local['zip']: |
|
886 | if dict_local['zip']: | |
887 | tempdir = tempfile.mkdtemp(prefix=kwargs['id']+'-')+self.separator |
|
887 | tempdir = tempfile.mkdtemp(prefix=kwargs['id']+'-')+self.separator | |
888 | os.mkdir(tempdir+kwargs['id']) |
|
888 | os.mkdir(tempdir+kwargs['id']) | |
889 | dir_name = tempdir + kwargs['id'] + self.separator |
|
889 | dir_name = tempdir + kwargs['id'] + self.separator | |
890 | else: |
|
890 | else: | |
891 | dir = self.f_name(kwargs['id'], '', dict_local['path']) |
|
891 | dir = self.f_name(kwargs['id'], '', dict_local['path']) | |
892 | os.mkdir(dict_local['path'] + dir) |
|
892 | os.mkdir(dict_local['path'] + dir) | |
893 | dir_name = dict_local['path'] + dir + self.separator |
|
893 | dir_name = dict_local['path'] + dir + self.separator | |
894 | #-----------DOWNLOAD FILES-------------# |
|
894 | #-----------DOWNLOAD FILES-------------# | |
895 | print('.....') |
|
895 | print('.....') | |
896 | print('Downloading "{}" file(s) >>'.format(len(response))) |
|
896 | print('Downloading "{}" file(s) >>'.format(len(response))) | |
897 | name_total = {'name': []} |
|
897 | name_total = {'name': []} | |
898 | with concurrent.futures.ThreadPoolExecutor() as executor: |
|
898 | with concurrent.futures.ThreadPoolExecutor() as executor: | |
899 | for u in tqdm(iterable=response, total=len(response)): |
|
899 | for u in tqdm(iterable=response, total=len(response)): | |
900 | name_total['name'].append(u['name']) |
|
900 | name_total['name'].append(u['name']) | |
901 | executor.submit(self.download_by_step, u, dir_name) |
|
901 | executor.submit(self.download_by_step, u, dir_name) | |
902 | name_check = {} |
|
902 | name_check = {} | |
903 | name_check['name'] = [f for f in os.listdir(dir_name) if os.path.isfile(os.path.join(dir_name, f))] |
|
903 | name_check['name'] = [f for f in os.listdir(dir_name) if os.path.isfile(os.path.join(dir_name, f))] | |
904 | print('"{}" downloaded file(s) successfully >>'.format(len(name_check['name']))) |
|
904 | print('"{}" downloaded file(s) successfully >>'.format(len(name_check['name']))) | |
905 | #--------------------------------------# |
|
905 | #--------------------------------------# | |
906 | if len(name_check['name']) != 0: |
|
906 | if len(name_check['name']) != 0: | |
907 | #----------Status Note---------# |
|
907 | #----------Status Note---------# | |
908 | if dict_local['status_note']: |
|
908 | if dict_local['status_note']: | |
909 | print('.....') |
|
909 | print('.....') | |
910 | print('Creating: "status_note.txt" >>') |
|
910 | print('Creating: "status_note.txt" >>') | |
911 | self.f_status_note(name_total, name_check, dir_name) |
|
911 | self.f_status_note(name_total, name_check, dir_name) | |
912 | print('Created>>') |
|
912 | print('Created>>') | |
913 | #----------ZIP CREATE----------# |
|
913 | #----------ZIP CREATE----------# | |
914 | if dict_local['zip']: |
|
914 | if dict_local['zip']: | |
915 | zip_name = self.f_name(kwargs['id'], '.zip', dict_local['path']) |
|
915 | zip_name = self.f_name(kwargs['id'], '.zip', dict_local['path']) | |
916 | ziph = zipfile.ZipFile(dict_local['path'] + zip_name, 'w', zipfile.ZIP_DEFLATED, allowZip64=True) |
|
916 | ziph = zipfile.ZipFile(dict_local['path'] + zip_name, 'w', zipfile.ZIP_DEFLATED, allowZip64=True) | |
917 | self.f_zipdir(dir_name, ziph, zip_name) |
|
917 | self.f_zipdir(dir_name, ziph, zip_name) | |
918 | ziph.close() |
|
918 | ziph.close() | |
919 | #Delete Temporal Path |
|
919 | #Delete Temporal Path | |
920 | if os.path.exists(tempdir[:-1]): |
|
920 | if os.path.exists(tempdir[:-1]): | |
921 | shutil.rmtree(tempdir[:-1]) |
|
921 | shutil.rmtree(tempdir[:-1]) | |
922 | #------------------------------# |
|
922 | #------------------------------# | |
923 | print('.....') |
|
923 | print('.....') | |
924 | return 'DOWNLOAD FINISHED' |
|
924 | return 'DOWNLOAD FINISHED' | |
925 | else: |
|
925 | else: | |
926 | #Delete Temporal Path |
|
926 | #Delete Temporal Path | |
927 | if dict_local['zip']: |
|
927 | if dict_local['zip']: | |
928 | if os.path.exists(tempdir[:-1]): |
|
928 | if os.path.exists(tempdir[:-1]): | |
929 | shutil.rmtree(tempdir[:-1]) |
|
929 | shutil.rmtree(tempdir[:-1]) | |
930 | else: |
|
930 | else: | |
931 | if os.path.exists(dir_name[:-1]): |
|
931 | if os.path.exists(dir_name[:-1]): | |
932 | shutil.rmtree(dir_name[:-1]) |
|
932 | shutil.rmtree(dir_name[:-1]) | |
933 | return 'NO FILES WERE DOWNLOADED' |
|
933 | return 'NO FILES WERE DOWNLOADED' | |
934 | else: |
|
934 | else: | |
935 | return 'FILES NOT FOUND' No newline at end of file |
|
935 | return 'FILES NOT FOUND' |
General Comments 0
You need to be logged in to leave comments.
Login now