bcpkgfox 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,39 @@
1
+ from .find_elements import *
2
+ from .invoke_api import *
3
+ from .get_driver import *
4
+ import os
5
+
6
+ download_dir = "C:\\TMPIMGGI\\LAST_IMG\\"
7
+ download_kit = "C:\\TMPIMGKIT\\"
8
+ download_ggi = "C:\\TMPIMGGI\\"
9
+ driver = None
10
+
11
+ def create_dirs():
12
+ global download_dir, download_kit, download_ggi
13
+ for directory in [download_dir, download_kit, download_ggi]:
14
+
15
+ if not os.path.exists(directory):
16
+ os.makedirs(directory)
17
+ print(f" - Diretório criado: {directory}")
18
+
19
+ def initialize_driver():
20
+ global driver
21
+ if driver is None:
22
+ driver = get_driver.launch_browser(download_dir)
23
+ return driver
24
+
25
+ def find_element_with_wait(by, value, timeout=10, parent=None):
26
+ global driver
27
+ if driver != None:
28
+ return find_elements.find_element_with_wait_backcode(driver, by, value, timeout, parent)
29
+
30
+ else: raise ValueError("Error: Driver is None")
31
+
32
+ def find_elements_with_wait(by, value, timeout=10, parent=None):
33
+ global driver
34
+ if driver != None:
35
+ return find_elements.find_elements_with_wait_backcode(driver, by, value, timeout, parent)
36
+
37
+ else: raise ValueError("Error: Driver is None")
38
+
39
+ print(" --> Biblioteca BCFOX Importada")
@@ -0,0 +1,19 @@
1
+ from selenium.webdriver.support import expected_conditions as EC
2
+ from selenium.webdriver.support.ui import WebDriverWait
3
+ from selenium import webdriver
4
+ from selenium.webdriver.common.by import By
5
+ from selenium.webdriver.common.keys import Keys
6
+
7
+ def find_element_with_wait_backcode(driver, by, value, timeout, parent):
8
+ if parent is None:
9
+ parent = driver # Usa o driver principal se nenhum elemento pai for passado
10
+ return WebDriverWait(parent, timeout).until(
11
+ EC.presence_of_element_located((by, value))
12
+ )
13
+
14
+ def find_elements_with_wait_backcode(driver, by, value, timeout, parent):
15
+ if parent is None:
16
+ parent = driver # Usa o driver principal se nenhum elemento pai for passado
17
+ return WebDriverWait(parent, timeout).until(
18
+ EC.presence_of_all_elements_located((by, value))
19
+ )
@@ -0,0 +1,44 @@
1
+ from selenium_stealth import stealth
2
+ import undetected_chromedriver as uc
3
+ import random
4
+ import sys
5
+ import os
6
+
7
+ # 1. Alterar o User-Agent
8
+ def set_user_agent():
9
+ user_agents = [
10
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36",
11
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36",
12
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
13
+ ]
14
+ return random.choice(user_agents)
15
+
16
+ # 2. Configurar e iniciar o navegador com undetected_chromedriver
17
+ def launch_browser(download_dir):
18
+ # Configurações para o Chrome
19
+ options = uc.ChromeOptions()
20
+
21
+ # Alterar o User-Agent
22
+ options.add_argument(f"user-agent={set_user_agent()}")
23
+
24
+ # Default's
25
+ profile = {
26
+ 'download.prompt_for_download': False,
27
+ 'download.directory_upgrade': True,
28
+ # 'plugins.always_open_pdf_externally': True, # É detectado como automação
29
+ 'download.default_directory': download_dir,
30
+ }
31
+
32
+ options.add_experimental_option('prefs', profile)
33
+
34
+ # Configurações para reduzir detecção
35
+ options.add_argument("--disable-blink-features=AutomationControlled")
36
+ options.add_argument("--disable-popup-blocking")
37
+ options.add_argument("--disable-infobars")
38
+ options.add_argument("--start-maximized")
39
+
40
+ # Inicializar o navegador com undetected_chromedriver
41
+ try: driver = uc.Chrome(options=options, use_subprocess=True)
42
+ except: driver = uc.Chrome(options=options, use_subprocess=True)
43
+
44
+ return driver
@@ -0,0 +1,283 @@
1
+ import requests
2
+
3
+ def invoke_api_list(link, uf, token, print_response="OFF"):
4
+ """
5
+ Exemplo de uso abaixo:
6
+
7
+ import BCFOX as bc
8
+
9
+ def invoke_api_list(self):
10
+ link = 'https://api-4.bcfox.com.br/bcjur/{parametros}'
11
+ token = 12345ABCDE12345ABCDE12345ABCDE12345ABCDE12345
12
+
13
+ bc.invoke_api_list(link, token, print_response='ON')
14
+
15
+ OBS: o print_response vem por padrão desligado, caso você queira ativa o print da view coloque 'ON'
16
+
17
+ """
18
+
19
+ url = f"https://api-4.bcfox.com.br/bcjur/views/{parametros}{uf}"
20
+
21
+ payload = ""
22
+ headers = {"x-access-token": token}
23
+
24
+ response = requests.request("GET", url, data=payload, headers=headers)
25
+
26
+ response_api_list = response.json()
27
+ if print_response == "ON":
28
+ print(f"Response API List: {response_api_list}")
29
+
30
+ return response_api_list
31
+
32
+ # ToDo: Continuar dps q validar as outras
33
+ # def invoke_depara_cliente():
34
+ # """
35
+ # Formato:
36
+ # invoke_depara_cliente(parametros, )
37
+ # - Parametros: https://api-4.bcfox.com.br/bcjur/views/depara/ { PARAMETROS/VAI/AQUI }
38
+ # """
39
+
40
+ # url = f"https://api-4.bcfox.com.br/bcjur/views/depara/{parametros}"
41
+
42
+ # payload = {}
43
+ # headers = {"x-access-token": token}
44
+ # max_attempts = 5
45
+ # for attempt in range(1, max_attempts + 1):
46
+ # try:
47
+ # response = requests.request("GET", url, json=payload, headers=headers)
48
+ # print(response.json())
49
+
50
+ # try:
51
+ # print(response.json()[0])
52
+ # gi.cliente = response.json()[0]['CLIENTE_BB']
53
+ # break
54
+ # except BaseException:
55
+ # gi.obs = "Cliente Invalido ou não configurado"
56
+ # self.exibir_messagebox("Atenção", f'Atenção! Cliente Invalido ou não configurado para gerar as custas \n cliente:{gi.cliente} idcliente: {gi.id_cliente} \n cnpj: {gi.cnpj_autor}')
57
+ # break
58
+ # except Exception as e:
59
+ # print(f"Tentativa {attempt} falhou: {e}")
60
+ # if attempt < max_attempts:
61
+ # print("Tentando novamente em 5 segundos...")
62
+ # time.sleep(5)
63
+ # continue
64
+ # else:
65
+ # raise ValueError("Error no depara cliente")
66
+
67
+ # def invoke_delete_guias():
68
+ # if gi.status != 3:
69
+
70
+ # url = f'https://api-4.bcfox.com.br/bcjur/{self.url}'
71
+
72
+ # payload = {"idguia": gi.id_tabela}
73
+
74
+ # headers = {"x-access-token": token}
75
+
76
+ # max_attempts = 5
77
+ # for attempt in range(1, max_attempts + 1):
78
+ # try:
79
+ # response = requests.delete(url, json=payload, headers=headers)
80
+ # # Lança uma exceção se a resposta não for bem-sucedida
81
+ # response.raise_for_status()
82
+ # print(response.json())
83
+ # print(f'{payload}, JSON: {response.json()}')
84
+ # status = response.json()[0]['STATUS']
85
+
86
+ # if status != 200:
87
+ # print('Erro ao deletar guias!')
88
+ # self.invoke_delete_guias()
89
+
90
+ # break
91
+
92
+ # except Exception as e:
93
+ # print(f"Tentativa {attempt} falhou: {e}")
94
+
95
+ # if attempt < max_attempts:
96
+ # print("Tentando novamente em 5 segundos...")
97
+ # time.sleep(5)
98
+ # continue
99
+
100
+ # else:
101
+ # raise ValueError("Erro no delete guias")
102
+
103
+ # def invoke_insere_guias():
104
+
105
+ # url = f'https://api-4.bcfox.com.br/bcjur/{self.url}'
106
+ # # gi.link_servidor = 'https://bcfiles.bcfox.com.br/docs/arquivos/'
107
+
108
+ # # ToDo: Ajustar variáveis quando tiver todas
109
+ # payload = {
110
+ # "idguia": gi.id_tabela,
111
+ # "numseq": 1,
112
+ # "status": gi.status,
113
+ # "nomearquivo": gi.nome_arquivo,
114
+ # "linkarquivo": f'{gi.link_servidor}{gi.nome_arquivo}',
115
+ # "linhadigitavel": gi.linha_digitavel
116
+ # }
117
+
118
+ # headers = {"x-access-token": token}
119
+
120
+ # max_attempts = 5
121
+ # for attempt in range(1, max_attempts + 1):
122
+ # try:
123
+ # response_insert = requests.post(url, json=payload, headers=headers)
124
+ # # Lança uma exceção se a resposta não for bem-sucedida
125
+ # response_insert.raise_for_status()
126
+ # print(f'Response.json: {response_insert.json()}')
127
+ # print(f'Payload: {payload}')
128
+ # status = response_insert.json()[0]['STATUS']
129
+
130
+ # if status != 200:
131
+ # print('Erro ao inserir guias!')
132
+ # self.invoke_insere_guias()
133
+
134
+ # gi.id_guia = response_insert.json()
135
+ # break
136
+
137
+ # except Exception as e:
138
+ # print(f"Tentativa {attempt} falhou: {e}")
139
+
140
+ # if attempt < max_attempts:
141
+ # print("Tentando novamente em 5 segundos...")
142
+ # time.sleep(5)
143
+ # continue
144
+
145
+ # else:
146
+ # raise ValueError("Erro no insere guias")
147
+
148
+ # def valida_qtd_itens():
149
+ # base_api_url = "https://api-4.bcfox.com.br/bcjur"
150
+ # url = f"{base_api_url}/views/guias/iniciais/valida/itens"
151
+ # self.tipo_guia = 'POS'
152
+
153
+ # payload = {
154
+ # "id": gi.id_tabela,
155
+ # "uf": self.uf,
156
+ # "tipo": self.tipo_guia,
157
+ # "tipoguia": 0
158
+ # }
159
+
160
+ # headers = {
161
+ # "x-access-token": token
162
+ # }
163
+
164
+ # max_attempts = 5
165
+
166
+ # for attempt in range(1, max_attempts + 1):
167
+ # try:
168
+ # response = requests.request("PATCH", url, headers=headers, data=payload)
169
+ # response_data = response.json()
170
+
171
+ # # Exibe o retorno da API
172
+ # print(response_data)
173
+
174
+ # # Trata o retorno da API
175
+ # status = response_data[0].get("STATUS")
176
+ # if status == 200:
177
+ # print("Validação OK!")
178
+ # print(f"Quantidade Real: {response_data[0].get('QUANTIDADE_REAL')}")
179
+ # print(f"Quantidade Atual: {response_data[0].get('QUANTIDADE_ATUAL')}")
180
+ # return status
181
+ # elif status == 400:
182
+ # print("Quantidade de arquivos no banco incorreta!")
183
+ # print("")
184
+ # self.exibir_messagebox(
185
+ # None, f"Quantidade que deveria ter: {
186
+ # response_data[0].get('QUANTIDADE_REAL')}\nQuantidade que possui: {
187
+ # response_data[0].get('QUANTIDADE_ATUAL')}\n")
188
+ # else:
189
+ # print("Resposta inesperada da API.")
190
+ # self.exibir_messagebox(None, "Resposta inesperada da API.")
191
+
192
+ # return response_data[0]
193
+
194
+ # except Exception as e:
195
+ # print(f"Tentativa {attempt} falhou: {e}")
196
+
197
+ # if attempt < max_attempts:
198
+ # print("Tentando novamente em 5 segundos...")
199
+ # time.sleep(5)
200
+ # else:
201
+ # print("Máximo de tentativas atingido. Falha ao validar quantidade de itens.")
202
+ # # Aqui pode ser adicionada uma ação caso o erro persista
203
+ # break
204
+
205
+ def invoke_api_proc_final(link_, payload_vars, token, print_response="OFF"):
206
+ """
207
+ Exemplo de uso abaixo:
208
+
209
+ import BCFOX as bc
210
+
211
+ def invoke_api_proc_final(self):
212
+ link = https://api-4.bcfox.com.br/bcjur/{parametros}
213
+ token = 12345ABCDE12345ABCDE12345ABCDE12345ABCDE12345
214
+
215
+ payload = [
216
+ {"ID":self.id},
217
+ {"STATUS":self.status},
218
+ {"PAGAMENTO":self.pagamento}
219
+ ...
220
+ ]
221
+
222
+ bc.invoke_api_proc_final(link, payload, token, print_response="ON")
223
+
224
+ OBS: o print_response vem por padrão desligado, caso você queria ver o returno do response coloque 'ON'
225
+
226
+ """
227
+ # ToDo: Finalizar validação
228
+ # PROC PARA FINALIZAR PROCESSO
229
+ url = link_
230
+
231
+ payload = payload_vars
232
+
233
+ if print_response == "ON":
234
+ print(f'payload: {payload}')
235
+
236
+ headers = {"x-access-token": token}
237
+
238
+ max_attempts = 5
239
+ for attempt in range(1, max_attempts + 1):
240
+ try:
241
+ response_insert = requests.put(url, json=payload, headers=headers)
242
+ # Lança uma exceção se a resposta não for bem-sucedida
243
+ response_insert.raise_for_status()
244
+ print(response_insert.json())
245
+ print(payload)
246
+
247
+ status = response_insert.json()[0]['STATUS']
248
+ print(status)
249
+
250
+ if status != 200:
251
+ print('Erro ao atualizar caso!')
252
+ self.invoke_api_proc_final()
253
+
254
+ return status
255
+
256
+ except Exception as e:
257
+ print(f"Tentativa {attempt} falhou: {e}")
258
+
259
+ if attempt < max_attempts:
260
+ print("Tentando novamente em 5 segundos...")
261
+ time.sleep(5)
262
+ continue
263
+
264
+ else:
265
+ raise ValueError("Api proc FINAL falhou")
266
+
267
+ def invoke_api_proc_log(id_robo, token):
268
+ """Só colocar o ID do robo e o Token direto """
269
+
270
+ url = "https://api-4.bcfox.com.br/bcjur/log"
271
+
272
+ payload = {
273
+ "id": id_robo
274
+ }
275
+
276
+ print(payload)
277
+
278
+ headers = {
279
+ "x-access-token": token}
280
+
281
+ responseinsert = requests.request(
282
+ "POST", url, json=payload, headers=headers)
283
+ print(responseinsert.json())
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 2.1
2
+ Name: bcpkgfox
3
+ Version: 0.0.1
4
+ Summary: Biblioteca BCFOX
5
+ Home-page: https://github.com/GuilhermNeri/PacotePythonBCFOX
6
+ Author: Guilherme Neri
7
+ Author-email: guilherme.neri@bcfox.com.br
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.6
12
+ Description-Content-Type: text/markdown
13
+ Requires-Dist: selenium
14
+ Requires-Dist: selenium-stealth
15
+ Requires-Dist: undetected-chromedriver
16
+ Requires-Dist: requests
@@ -0,0 +1,59 @@
1
+ #nota Token único api: pypi-AgEIcHlwaS5vcmcCJDNiOTVjMjFlLTdiNWEtNGY1OC1hYmUxLTBiODQ0ZjM5MGJjYQACKlszLCI2MjE4YTk4OC1hOTg3LTQ4ODAtOGQ4MC0wZDZlNzZiZDE3NTMiXQAABiCpcLmagfgWs5kIeHr_0k3jDMXjsyRD51lu3Cs2X_3LIQ
2
+
3
+
4
+ Para lançar uma versão nova da bibliotca:
5
+
6
+ - 1° Verifique se você tem o arquivo de autenticação .pypirc:
7
+ Na pasta de do seu usuário (C:\Users\eliezer.gimenes), deve conter o arquivo com o nome ".pypirc"
8
+ E dentro dele tem que ter o seguinte conteúdo:
9
+
10
+ """
11
+ [distutils]
12
+ index-servers =
13
+ pypi
14
+
15
+ [pypi]
16
+ repository: https://upload.pypi.org/legacy/
17
+ username = bcfoxtecnologia
18
+ password = pypi-AgEIcHlwaS5vcmcCJDNiOTVjMjFlLTdiNWEtNGY1OC1hYmUxLTBiODQ0ZjM5MGJjYQACKlszLCI2MjE4YTk4OC1hOTg3LTQ4ODAtOGQ4MC0wZDZlNzZiZDE3NTMiXQAABiCpcLmagfgWs5kIeHr_0k3jDMXjsyRD51lu3Cs2X_3LIQ
19
+ """
20
+
21
+ - 2° Instale essas bibliotecas:
22
+ pip install setuptools twine
23
+
24
+ - 3° Depois de ter altualizado o código da biblioteca, mude a versão no arquivo chamado "Setup.py"
25
+ Exemplo:
26
+ Na linha 'version="0.1.5"' mude para a versão seguinte, 'version="0.1.6"'
27
+
28
+ - 4° Salve o setup.py e gere o novo executável:
29
+ Abra um terminal no diretório do arquivo e cole o seguinte comando:
30
+ 'python setup.py sdist bdist_wheel'
31
+
32
+ - 5° Remova a versão antiga:
33
+ Depois de ter gerado o comando de exec, terá a versão nova e a antiga dentro da pasta dist
34
+ Apague o .whl e o .tar.gz da versão antiga
35
+
36
+ Exemplo:
37
+ BCFOX/
38
+ │
39
+ ├── BCFOX/
40
+ │
41
+ ├── BCFOX.egg-info/
42
+ │
43
+ ├── build/
44
+ │
45
+ ├── dist/
46
+ │ ├── BCFOX-0.1.5-py3-none-any.whl (apagar)
47
+ │ ├── BCFOX-0.1.6-py3-none-any.whl (versão nova)
48
+ │ │
49
+ │ ├── bcfox-0.1.5.tar.gz (apagar)
50
+ │ └── bcfox-0.1.6.tar.gz (versão nova)
51
+ │
52
+ ├── lib/
53
+ │
54
+ ├── README.md
55
+ └── setup.py
56
+
57
+ - 6° Push:
58
+ Em um terminal dentro de repositório:
59
+ twine upload dist/*
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 2.1
2
+ Name: bcpkgfox
3
+ Version: 0.0.1
4
+ Summary: Biblioteca BCFOX
5
+ Home-page: https://github.com/GuilhermNeri/PacotePythonBCFOX
6
+ Author: Guilherme Neri
7
+ Author-email: guilherme.neri@bcfox.com.br
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.6
12
+ Description-Content-Type: text/markdown
13
+ Requires-Dist: selenium
14
+ Requires-Dist: selenium-stealth
15
+ Requires-Dist: undetected-chromedriver
16
+ Requires-Dist: requests
@@ -0,0 +1,11 @@
1
+ README.txt
2
+ setup.py
3
+ BCFOX/__init__.py
4
+ BCFOX/find_elements.py
5
+ BCFOX/get_driver.py
6
+ BCFOX/invoke_api.py
7
+ bcpkgfox.egg-info/PKG-INFO
8
+ bcpkgfox.egg-info/SOURCES.txt
9
+ bcpkgfox.egg-info/dependency_links.txt
10
+ bcpkgfox.egg-info/requires.txt
11
+ bcpkgfox.egg-info/top_level.txt
@@ -0,0 +1,4 @@
1
+ selenium
2
+ selenium-stealth
3
+ undetected-chromedriver
4
+ requests
@@ -0,0 +1 @@
1
+ BCFOX
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,25 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name="bcpkgfox",
5
+ version="0.0.1",
6
+ author="Guilherme Neri",
7
+ author_email="guilherme.neri@bcfox.com.br",
8
+ description="Biblioteca BCFOX",
9
+ long_description=open("README.md").read(),
10
+ long_description_content_type="text/markdown",
11
+ url="https://github.com/GuilhermNeri/PacotePythonBCFOX",
12
+ packages=find_packages(),
13
+ classifiers=[
14
+ "Programming Language :: Python :: 3",
15
+ "License :: OSI Approved :: MIT License",
16
+ "Operating System :: OS Independent",
17
+ ],
18
+ python_requires=">=3.6",
19
+ install_requires=[
20
+ 'selenium', # Selenium para automação
21
+ 'selenium-stealth', # Selenium Stealth para ocultar o driver
22
+ 'undetected-chromedriver', # Para usar o Chrome com contorno de proteção
23
+ 'requests', # Para fazer requisições HTTP
24
+ ],
25
+ )