csctracker-py-core 26.7.4__tar.gz → 26.7.7__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.
Files changed (28) hide show
  1. csctracker_py_core-26.7.7/PKG-INFO +157 -0
  2. csctracker_py_core-26.7.7/README.md +107 -0
  3. {csctracker_py_core-26.7.4 → csctracker_py_core-26.7.7}/csctracker_py_core/repository/http_repository.py +74 -39
  4. {csctracker_py_core-26.7.4 → csctracker_py_core-26.7.7}/csctracker_py_core/repository/remote_repository.py +36 -21
  5. {csctracker_py_core-26.7.4 → csctracker_py_core-26.7.7}/csctracker_py_core/starter.py +11 -10
  6. {csctracker_py_core-26.7.4 → csctracker_py_core-26.7.7}/csctracker_py_core/utils/configs.py +17 -14
  7. {csctracker_py_core-26.7.4 → csctracker_py_core-26.7.7}/csctracker_py_core/utils/interceptor.py +26 -24
  8. {csctracker_py_core-26.7.4 → csctracker_py_core-26.7.7}/csctracker_py_core/utils/request_info.py +4 -2
  9. {csctracker_py_core-26.7.4 → csctracker_py_core-26.7.7}/csctracker_py_core/utils/utils.py +12 -8
  10. {csctracker_py_core-26.7.4 → csctracker_py_core-26.7.7}/csctracker_py_core/utils/version.py +3 -3
  11. csctracker_py_core-26.7.7/csctracker_py_core.egg-info/PKG-INFO +157 -0
  12. csctracker_py_core-26.7.7/setup.py +59 -0
  13. csctracker_py_core-26.7.4/PKG-INFO +0 -57
  14. csctracker_py_core-26.7.4/README.md +0 -20
  15. csctracker_py_core-26.7.4/csctracker_py_core.egg-info/PKG-INFO +0 -57
  16. csctracker_py_core-26.7.4/setup.py +0 -32
  17. {csctracker_py_core-26.7.4 → csctracker_py_core-26.7.7}/LICENSE +0 -0
  18. {csctracker_py_core-26.7.4 → csctracker_py_core-26.7.7}/csctracker_py_core/__init__.py +0 -0
  19. {csctracker_py_core-26.7.4 → csctracker_py_core-26.7.7}/csctracker_py_core/models/__init__.py +0 -0
  20. {csctracker_py_core-26.7.4 → csctracker_py_core-26.7.7}/csctracker_py_core/models/emuns/__init__.py +0 -0
  21. {csctracker_py_core-26.7.4 → csctracker_py_core-26.7.7}/csctracker_py_core/models/emuns/config.py +0 -0
  22. {csctracker_py_core-26.7.4 → csctracker_py_core-26.7.7}/csctracker_py_core/repository/__init__.py +0 -0
  23. {csctracker_py_core-26.7.4 → csctracker_py_core-26.7.7}/csctracker_py_core/utils/__init__.py +0 -0
  24. {csctracker_py_core-26.7.4 → csctracker_py_core-26.7.7}/csctracker_py_core.egg-info/SOURCES.txt +0 -0
  25. {csctracker_py_core-26.7.4 → csctracker_py_core-26.7.7}/csctracker_py_core.egg-info/dependency_links.txt +0 -0
  26. {csctracker_py_core-26.7.4 → csctracker_py_core-26.7.7}/csctracker_py_core.egg-info/requires.txt +0 -0
  27. {csctracker_py_core-26.7.4 → csctracker_py_core-26.7.7}/csctracker_py_core.egg-info/top_level.txt +0 -0
  28. {csctracker_py_core-26.7.4 → csctracker_py_core-26.7.7}/setup.cfg +0 -0
@@ -0,0 +1,157 @@
1
+ Metadata-Version: 2.4
2
+ Name: csctracker-py-core
3
+ Version: 26.7.7
4
+ Summary: A base library for microservices with Flask, JSON logging, and Prometheus telemetry.
5
+ Home-page: https://github.com/krlsedu/CscTrackerPyCore
6
+ Author: Carlos Eduardo
7
+ License: MIT
8
+ Project-URL: Bug Tracker, https://github.com/krlsedu/CscTrackerPyCore/issues
9
+ Project-URL: Source Code, https://github.com/krlsedu/CscTrackerPyCore
10
+ Keywords: microservices,flask,json-logging,prometheus,telemetry,swagger,openapi,background-jobs,scheduler,observability,http-client,middleware
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Information Technology
14
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
15
+ Classifier: Topic :: System :: Logging
16
+ Classifier: Topic :: System :: Monitoring
17
+ Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware
18
+ Classifier: License :: OSI Approved :: MIT License
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.9
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Operating System :: OS Independent
25
+ Requires-Python: >=3.9
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Requires-Dist: csctracker-queue-scheduler==24.6.1
29
+ Requires-Dist: flask~=3.0.0
30
+ Requires-Dist: python-json-logger
31
+ Requires-Dist: python-dotenv~=1.0.0
32
+ Requires-Dist: requests~=2.32.0
33
+ Requires-Dist: beautifulsoup4==4.10.0
34
+ Requires-Dist: flask-cors~=3.0.7
35
+ Requires-Dist: prometheus-flask-exporter==0.22.4
36
+ Requires-Dist: flask-swagger-init==23.52.4
37
+ Requires-Dist: pytz~=2023.3.post1
38
+ Dynamic: author
39
+ Dynamic: classifier
40
+ Dynamic: description
41
+ Dynamic: description-content-type
42
+ Dynamic: home-page
43
+ Dynamic: keywords
44
+ Dynamic: license
45
+ Dynamic: license-file
46
+ Dynamic: project-url
47
+ Dynamic: requires-dist
48
+ Dynamic: requires-python
49
+ Dynamic: summary
50
+
51
+ # CscTrackerPyCore
52
+
53
+ [![PyPI version](https://img.shields.io/pypi/v/csctracker-py-core.svg)](https://pypi.org/project/csctracker-py-core/)
54
+ [![Python versions](https://img.shields.io/pypi/pyversions/csctracker-py-core.svg)](https://pypi.org/project/csctracker-py-core/)
55
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
56
+ [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
57
+
58
+ CscTrackerPyCore é uma biblioteca Python base desenvolvida para padronizar e acelerar o desenvolvimento de microserviços. Ela oferece integração nativa com Flask, fornecendo recursos essenciais como logging estruturado em JSON, telemetria com Prometheus, documentação automática via Swagger e gerenciamento de tarefas agendadas.
59
+
60
+ ## Principais Funcionalidades
61
+
62
+ - **Starter Facilitado**: Inicialização rápida de aplicações Flask com suporte a CORS e tratamento de variáveis de ambiente.
63
+ - **Logging Estruturado**: Formatação automática de logs em JSON com inclusão de `requestId`, `appName` e `appVersion` para melhor rastreabilidade.
64
+ - **Observabilidade**:
65
+ - Integração nativa com **Prometheus** para coleta de métricas de endpoints.
66
+ - **Interceptor de Requisições**: Registro detalhado de chamadas HTTP (método, path, status, duração) com opção de persistência remota para auditoria.
67
+ - **Documentação Automática**: Geração de especificação **Swagger (OpenAPI)** simplificada.
68
+ - **Processamento em Background**: Integração com `csctracker-queue-scheduler` para execução de tarefas assíncronas e agendadas.
69
+ - **Repositórios Remotos**: Abstração para comunicação entre serviços via HTTP com tratamento de headers e correlação.
70
+
71
+ ## Requisitos
72
+
73
+ - Python 3.9+
74
+ - Flask
75
+ - Flask-CORS
76
+ - Prometheus Flask Exporter
77
+ - Flask Swagger Generator
78
+ - Python JSON Logger
79
+ - Python Dotenv
80
+
81
+ ## Instalação
82
+
83
+ As dependências podem ser instaladas via `pip`:
84
+
85
+ ```bash
86
+ pip install csctracker-py-core
87
+ ```
88
+
89
+ Ou via `requirements.txt`:
90
+
91
+ ```bash
92
+ pip install -r requirements.txt
93
+ ```
94
+
95
+ ## Configuração
96
+
97
+ A biblioteca é configurada principalmente via variáveis de ambiente, suportando arquivos `.env` localizados na pasta `config/` (ex: `config/dev.env`).
98
+
99
+ ### Variáveis de Ambiente Suportadas
100
+
101
+ | Variável | Descrição | Exemplo |
102
+ | :--- | :--- | :--- |
103
+ | `PROFILE` | Perfil de configuração (define o arquivo .env) | `dev` |
104
+ | `PORT` | Porta de execução do servidor Flask | `5000` |
105
+ | `LOG_LEVEL` | Nível de detalhamento do log | `INFO`, `DEBUG` |
106
+ | `LOG_REQUEST_BODY` | Se `True`, inclui o corpo da requisição nos logs | `True` |
107
+ | `LOG_RESPONSE_BODY` | Se `True`, inclui o corpo da resposta nos logs | `False` |
108
+ | `URL_BFF` | URL base para persistência de logs de requisição | `http://api-gateway/` |
109
+ | `API_TOKEN` | Token de autorização para chamadas externas | `seu_token_aqui` |
110
+ | `DEBUG` | Ativa o modo debug do Flask se definido como `1` | `0` |
111
+
112
+ ## Uso Didático
113
+
114
+ ### 1. Inicialização do `Starter`
115
+
116
+ A classe `Starter` centraliza a configuração do Flask.
117
+
118
+ ```python
119
+ from csctracker_py_core.starter import Starter
120
+
121
+ # Inicializa o starter (static_folder define a pasta de arquivos estáticos)
122
+ # save_request=True ativa a persistência remota de logs de requisição
123
+ starter = Starter(save_request=False)
124
+
125
+ # Obtém a instância do Flask configurada
126
+ app = starter.get_app()
127
+
128
+ @app.route('/')
129
+ def hello():
130
+ return {"message": "CscTrackerPyCore is running!"}
131
+
132
+ if __name__ == '__main__':
133
+ starter.start()
134
+ ```
135
+
136
+ ### 2. Logging e Interceptação
137
+
138
+ Uma vez iniciado o `Starter`, todos os logs do sistema usarão o formato JSON e as requisições serão interceptadas automaticamente para gerar telemetria.
139
+
140
+ ### 3. Acesso aos Repositórios
141
+
142
+ ```python
143
+ # Acesso ao repositório HTTP para chamadas externas padronizadas
144
+ http_repo = starter.get_http_repository()
145
+ ```
146
+
147
+ ## Estrutura do Projeto
148
+
149
+ - `Starter`: Orquestrador principal que configura Flask, CORS, Métricas e Swagger.
150
+ - `Configs`: Gerencia o carregamento de variáveis de ambiente e a configuração do logger JSON.
151
+ - `Interceptor`: Middleware Flask que captura dados de performance e logs de entrada/saída.
152
+ - `HttpRepository`: Facilita requisições HTTP externas com injeção de headers de segurança e rastreio.
153
+ - `RequestInfo`: Utilitário para gerenciar IDs de correlação (Correlation IDs) entre threads.
154
+
155
+ ## Licença
156
+
157
+ Este projeto está sob a licença MIT. Consulte o arquivo `LICENSE` para mais detalhes.
@@ -0,0 +1,107 @@
1
+ # CscTrackerPyCore
2
+
3
+ [![PyPI version](https://img.shields.io/pypi/v/csctracker-py-core.svg)](https://pypi.org/project/csctracker-py-core/)
4
+ [![Python versions](https://img.shields.io/pypi/pyversions/csctracker-py-core.svg)](https://pypi.org/project/csctracker-py-core/)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
+ [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
7
+
8
+ CscTrackerPyCore é uma biblioteca Python base desenvolvida para padronizar e acelerar o desenvolvimento de microserviços. Ela oferece integração nativa com Flask, fornecendo recursos essenciais como logging estruturado em JSON, telemetria com Prometheus, documentação automática via Swagger e gerenciamento de tarefas agendadas.
9
+
10
+ ## Principais Funcionalidades
11
+
12
+ - **Starter Facilitado**: Inicialização rápida de aplicações Flask com suporte a CORS e tratamento de variáveis de ambiente.
13
+ - **Logging Estruturado**: Formatação automática de logs em JSON com inclusão de `requestId`, `appName` e `appVersion` para melhor rastreabilidade.
14
+ - **Observabilidade**:
15
+ - Integração nativa com **Prometheus** para coleta de métricas de endpoints.
16
+ - **Interceptor de Requisições**: Registro detalhado de chamadas HTTP (método, path, status, duração) com opção de persistência remota para auditoria.
17
+ - **Documentação Automática**: Geração de especificação **Swagger (OpenAPI)** simplificada.
18
+ - **Processamento em Background**: Integração com `csctracker-queue-scheduler` para execução de tarefas assíncronas e agendadas.
19
+ - **Repositórios Remotos**: Abstração para comunicação entre serviços via HTTP com tratamento de headers e correlação.
20
+
21
+ ## Requisitos
22
+
23
+ - Python 3.9+
24
+ - Flask
25
+ - Flask-CORS
26
+ - Prometheus Flask Exporter
27
+ - Flask Swagger Generator
28
+ - Python JSON Logger
29
+ - Python Dotenv
30
+
31
+ ## Instalação
32
+
33
+ As dependências podem ser instaladas via `pip`:
34
+
35
+ ```bash
36
+ pip install csctracker-py-core
37
+ ```
38
+
39
+ Ou via `requirements.txt`:
40
+
41
+ ```bash
42
+ pip install -r requirements.txt
43
+ ```
44
+
45
+ ## Configuração
46
+
47
+ A biblioteca é configurada principalmente via variáveis de ambiente, suportando arquivos `.env` localizados na pasta `config/` (ex: `config/dev.env`).
48
+
49
+ ### Variáveis de Ambiente Suportadas
50
+
51
+ | Variável | Descrição | Exemplo |
52
+ | :--- | :--- | :--- |
53
+ | `PROFILE` | Perfil de configuração (define o arquivo .env) | `dev` |
54
+ | `PORT` | Porta de execução do servidor Flask | `5000` |
55
+ | `LOG_LEVEL` | Nível de detalhamento do log | `INFO`, `DEBUG` |
56
+ | `LOG_REQUEST_BODY` | Se `True`, inclui o corpo da requisição nos logs | `True` |
57
+ | `LOG_RESPONSE_BODY` | Se `True`, inclui o corpo da resposta nos logs | `False` |
58
+ | `URL_BFF` | URL base para persistência de logs de requisição | `http://api-gateway/` |
59
+ | `API_TOKEN` | Token de autorização para chamadas externas | `seu_token_aqui` |
60
+ | `DEBUG` | Ativa o modo debug do Flask se definido como `1` | `0` |
61
+
62
+ ## Uso Didático
63
+
64
+ ### 1. Inicialização do `Starter`
65
+
66
+ A classe `Starter` centraliza a configuração do Flask.
67
+
68
+ ```python
69
+ from csctracker_py_core.starter import Starter
70
+
71
+ # Inicializa o starter (static_folder define a pasta de arquivos estáticos)
72
+ # save_request=True ativa a persistência remota de logs de requisição
73
+ starter = Starter(save_request=False)
74
+
75
+ # Obtém a instância do Flask configurada
76
+ app = starter.get_app()
77
+
78
+ @app.route('/')
79
+ def hello():
80
+ return {"message": "CscTrackerPyCore is running!"}
81
+
82
+ if __name__ == '__main__':
83
+ starter.start()
84
+ ```
85
+
86
+ ### 2. Logging e Interceptação
87
+
88
+ Uma vez iniciado o `Starter`, todos os logs do sistema usarão o formato JSON e as requisições serão interceptadas automaticamente para gerar telemetria.
89
+
90
+ ### 3. Acesso aos Repositórios
91
+
92
+ ```python
93
+ # Acesso ao repositório HTTP para chamadas externas padronizadas
94
+ http_repo = starter.get_http_repository()
95
+ ```
96
+
97
+ ## Estrutura do Projeto
98
+
99
+ - `Starter`: Orquestrador principal que configura Flask, CORS, Métricas e Swagger.
100
+ - `Configs`: Gerencia o carregamento de variáveis de ambiente e a configuração do logger JSON.
101
+ - `Interceptor`: Middleware Flask que captura dados de performance e logs de entrada/saída.
102
+ - `HttpRepository`: Facilita requisições HTTP externas com injeção de headers de segurança e rastreio.
103
+ - `RequestInfo`: Utilitário para gerenciar IDs de correlação (Correlation IDs) entre threads.
104
+
105
+ ## Licença
106
+
107
+ Este projeto está sob a licença MIT. Consulte o arquivo `LICENSE` para mais detalhes.
@@ -11,8 +11,8 @@ from csctracker_py_core.utils.configs import Configs
11
11
  from csctracker_py_core.utils.request_info import RequestInfo
12
12
 
13
13
  headers_sti = {
14
- 'Cookie': Configs.get_env_variable(Config.STI_COOKIE),
15
- 'User-Agent': 'PostmanRuntime/7.26.8'
14
+ "Cookie": Configs.get_env_variable(Config.STI_COOKIE),
15
+ "User-Agent": "PostmanRuntime/7.26.8",
16
16
  }
17
17
 
18
18
 
@@ -22,8 +22,11 @@ class HttpRepository:
22
22
  pass
23
23
 
24
24
  def get_stock_type(self, ticker, headers=None):
25
- response = requests.get('https://statusinvest.com.br/home/mainsearchquery', params={"q": ticker},
26
- headers=headers_sti)
25
+ response = requests.get(
26
+ "https://statusinvest.com.br/home/mainsearchquery",
27
+ params={"q": ticker},
28
+ headers=headers_sti,
29
+ )
27
30
  return response.json()
28
31
 
29
32
  def get_firt_stock_type(self, ticker, headers=None):
@@ -31,8 +34,12 @@ class HttpRepository:
31
34
 
32
35
  # FIXME: importar o remote_repository.py
33
36
  def get_page_text(self, ticker, headers=None):
34
- stock = self.remote_repository.get_object("stocks", ["ticker"], {"ticker": ticker}, headers)
35
- page = requests.get(f"https://statusinvest.com.br{stock['url_infos']}", headers=headers_sti)
37
+ stock = self.remote_repository.get_object(
38
+ "stocks", ["ticker"], {"ticker": ticker}, headers
39
+ )
40
+ page = requests.get(
41
+ f"https://statusinvest.com.br{stock['url_infos']}", headers=headers_sti
42
+ )
36
43
  return page.text
37
44
 
38
45
  def get_page_text_by_url(self, url, headers=None):
@@ -41,7 +48,9 @@ class HttpRepository:
41
48
 
42
49
  def get_values_by_ticker(self, stock, force=False, headers=None, time_multiply=1):
43
50
  try:
44
- last_update = datetime.strptime(stock['last_update'], '%Y-%m-%d %H:%M:%S.%f').replace(tzinfo=timezone.utc)
51
+ last_update = datetime.strptime(
52
+ stock["last_update"], "%Y-%m-%d %H:%M:%S.%f"
53
+ ).replace(tzinfo=timezone.utc)
45
54
  astimezone = datetime.now().astimezone(timezone.utc)
46
55
  time = astimezone.timestamp() * 1000 - last_update.timestamp() * 1000
47
56
  queue = time > (1000 * 60 * 15 * time_multiply) or time < 0
@@ -49,22 +58,24 @@ class HttpRepository:
49
58
  queue = True
50
59
  if queue or force:
51
60
  try:
52
- text = self.get_page_text(stock['ticker'], headers)
61
+ text = self.get_page_text(stock["ticker"], headers)
53
62
  soup = BeautifulSoup(text, "html5lib")
54
63
  self.get_values(soup, stock)
55
64
  try:
56
65
  if stock["investment_type_id"] <= 4:
57
- stock['pvp'] = self.get_info(stock, "vp", headers)
66
+ stock["pvp"] = self.get_info(stock, "vp", headers)
58
67
  except Exception as e:
59
- print(e, stock['ticker'], "pvp")
68
+ print(e, stock["ticker"], "pvp")
60
69
  pass
61
- self.remote_repository.update("stocks", ['ticker'], stock, headers)
70
+ self.remote_repository.update("stocks", ["ticker"], stock, headers)
62
71
  except Exception as e:
63
72
  print(e)
64
73
  pass
65
- investment_type = self.remote_repository.get_object("investment_types",
66
- data={"id": stock['investment_type_id']},
67
- headers=headers)
74
+ investment_type = self.remote_repository.get_object(
75
+ "investment_types",
76
+ data={"id": stock["investment_type_id"]},
77
+ headers=headers,
78
+ )
68
79
  return stock, investment_type, queue
69
80
 
70
81
  def get_soup(self, url, headers=None):
@@ -77,10 +88,14 @@ class HttpRepository:
77
88
  stock["segment"] = self.find_value(soup, "Segmento", "text", 2, 0)
78
89
  except:
79
90
  try:
80
- stock["segment"] = self.find_value(soup, "Segmento de Atuação", "text", 2, 0)
91
+ stock["segment"] = self.find_value(
92
+ soup, "Segmento de Atuação", "text", 2, 0
93
+ )
81
94
  except:
82
95
  try:
83
- stock["segment"] = self.find_value(soup, "\nClasse anbima\n", "text", 2, 0)
96
+ stock["segment"] = self.find_value(
97
+ soup, "\nClasse anbima\n", "text", 2, 0
98
+ )
84
99
  except:
85
100
  pass
86
101
 
@@ -116,22 +131,31 @@ class HttpRepository:
116
131
  return stock
117
132
 
118
133
  def get_info(self, stock_, atributo, headers=None, tag="span", is_number=True):
119
- url_ = 'https://investidor10.com.br/fiis/' + stock_['ticker']
120
- if stock_['investment_type_id'] == 1:
121
- url_ = 'https://investidor10.com.br/acoes/' + stock_['ticker']
122
- elif stock_['investment_type_id'] == 4:
123
- url_ = 'https://investidor10.com.br/bdrs/' + stock_['ticker']
124
- elif stock_['investment_type_id'] == 1001:
125
- ticker_ = ''.join([i for i in stock_['ticker'] if not i.isdigit()])
126
- url_ = 'https://investidor10.com.br/indices/' + ticker_
134
+ url_ = "https://investidor10.com.br/fiis/" + stock_["ticker"]
135
+ if stock_["investment_type_id"] == 1:
136
+ url_ = "https://investidor10.com.br/acoes/" + stock_["ticker"]
137
+ elif stock_["investment_type_id"] == 4:
138
+ url_ = "https://investidor10.com.br/bdrs/" + stock_["ticker"]
139
+ elif stock_["investment_type_id"] == 1001:
140
+ ticker_ = "".join([i for i in stock_["ticker"] if not i.isdigit()])
141
+ url_ = "https://investidor10.com.br/indices/" + ticker_
127
142
  soup_ = self.get_soup(url_, headers)
128
- value_ = self.find_value(soup_, '_card ' + atributo, "class")[0]
129
- value_ = self.find_value(value_, '_card-body', "class")[0].find_all(tag)[0].text
143
+ value_ = self.find_value(soup_, "_card " + atributo, "class")[0]
144
+ value_ = self.find_value(value_, "_card-body", "class")[0].find_all(tag)[0].text
130
145
  if is_number:
131
146
  value_ = float(value_.replace(".", "").replace(",", "."))
132
147
  return value_
133
148
 
134
- def find_value(self, soup, text, type, parents=0, children=None, child_Type="strong", value="text"):
149
+ def find_value(
150
+ self,
151
+ soup,
152
+ text,
153
+ type,
154
+ parents=0,
155
+ children=None,
156
+ child_Type="strong",
157
+ value="text",
158
+ ):
135
159
  if type == "text":
136
160
  obj = soup.find_all(text=f"{text}")
137
161
  elif type == "class":
@@ -158,23 +182,34 @@ class HttpRepository:
158
182
 
159
183
  def get_prices(self, ticker, type, daily=False, price_type="4"):
160
184
  if daily:
161
- response = requests.get(f'https://statusinvest.com.br/{type}/tickerprice?type=-1&currences%5B%5D=1',
162
- params={"ticker": ticker}, headers=headers_sti)
185
+ response = requests.get(
186
+ f"https://statusinvest.com.br/{type}/tickerprice?type=-1&currences%5B%5D=1",
187
+ params={"ticker": ticker},
188
+ headers=headers_sti,
189
+ )
163
190
  else:
164
191
  response = requests.get(
165
- f'https://statusinvest.com.br/{type}/tickerprice?type={price_type}&currences%5B%5D=1',
166
- params={"ticker": ticker}, headers=headers_sti)
192
+ f"https://statusinvest.com.br/{type}/tickerprice?type={price_type}&currences%5B%5D=1",
193
+ params={"ticker": ticker},
194
+ headers=headers_sti,
195
+ )
167
196
  return response.json()
168
197
 
169
198
  def get_prices_fundos(self, ticker, month=False):
170
199
  if month:
171
- response = requests.get(f'https://statusinvest.com.br/fundoinvestimento/profitabilitymainresult?'
172
- f'nome_clean={ticker}'
173
- f'&time=1', headers=headers_sti)
200
+ response = requests.get(
201
+ f"https://statusinvest.com.br/fundoinvestimento/profitabilitymainresult?"
202
+ f"nome_clean={ticker}"
203
+ f"&time=1",
204
+ headers=headers_sti,
205
+ )
174
206
  else:
175
- response = requests.get(f'https://statusinvest.com.br/fundoinvestimento/profitabilitymainresult?'
176
- f'nome_clean={ticker}'
177
- f'&time=6', headers=headers_sti)
207
+ response = requests.get(
208
+ f"https://statusinvest.com.br/fundoinvestimento/profitabilitymainresult?"
209
+ f"nome_clean={ticker}"
210
+ f"&time=6",
211
+ headers=headers_sti,
212
+ )
178
213
  return response.json()
179
214
 
180
215
  def get(self, url, params={}, headers=None, body=None):
@@ -199,8 +234,8 @@ class HttpRepository:
199
234
  headers_ = {}
200
235
  for key in headers.keys():
201
236
  headers_[key] = headers.get(key)
202
- if 'x-correlation-id' not in headers_:
203
- headers_['x-correlation-id'] = RequestInfo.get_request_id(True)
237
+ if "x-correlation-id" not in headers_:
238
+ headers_["x-correlation-id"] = RequestInfo.get_request_id(True)
204
239
  return headers
205
240
 
206
241
  def get_request(self):
@@ -9,16 +9,20 @@ from csctracker_py_core.utils.configs import Configs
9
9
  class RemoteRepository:
10
10
  def __init__(self):
11
11
  self.logger = logging.getLogger()
12
- self.url_repository = Configs.get_env_variable(Config.URL_REPOSITORY, default='http://bff:8080/repository/')
13
- if self.url_repository[-1] != '/':
14
- self.url_repository += '/'
12
+ self.url_repository = Configs.get_env_variable(
13
+ Config.URL_REPOSITORY, default="http://bff:8080/repository/"
14
+ )
15
+ if self.url_repository[-1] != "/":
16
+ self.url_repository += "/"
15
17
  pass
16
18
 
17
19
  def insert(self, table, data, headers=None):
18
20
  try:
19
- response = requests.post(self.url_repository + table, headers=headers, json=data)
21
+ response = requests.post(
22
+ self.url_repository + table, headers=headers, json=data
23
+ )
20
24
  if response.status_code < 200 or response.status_code > 299:
21
- raise Exception(f'Error inserting data: {response.text}')
25
+ raise Exception(f"Error inserting data: {response.text}")
22
26
  return response.json()
23
27
  except Exception as e:
24
28
  raise e
@@ -26,9 +30,11 @@ class RemoteRepository:
26
30
  def update(self, table, keys=None, data=None, headers=None):
27
31
  params = self.get_params(data, keys)
28
32
  try:
29
- response = requests.post(self.url_repository + table, headers=headers, json=data, params=params)
33
+ response = requests.post(
34
+ self.url_repository + table, headers=headers, json=data, params=params
35
+ )
30
36
  if response.status_code < 200 or response.status_code > 299:
31
- raise Exception(f'Error updating data: {response.text}')
37
+ raise Exception(f"Error updating data: {response.text}")
32
38
  return response.json()
33
39
  except Exception as e:
34
40
  raise e
@@ -39,22 +45,27 @@ class RemoteRepository:
39
45
  def delete(self, table, keys=None, data=None, headers=None):
40
46
  params = self.get_params(data, keys)
41
47
  try:
42
- response = requests.post(self.url_repository + "delete/" + table, headers=headers, json=data, params=params)
48
+ response = requests.post(
49
+ self.url_repository + "delete/" + table,
50
+ headers=headers,
51
+ json=data,
52
+ params=params,
53
+ )
43
54
  if response.status_code < 200 or response.status_code > 299:
44
- raise Exception(f'Error deleting data: {response.text}')
55
+ raise Exception(f"Error deleting data: {response.text}")
45
56
  return response.json()
46
57
  except Exception as e:
47
58
  raise e
48
59
 
49
60
  def add_user_id(self, data, headers=None):
50
61
  user = self.get_user(headers)
51
- data['user_id'] = user['id']
62
+ data["user_id"] = user["id"]
52
63
  return data
53
64
 
54
65
  def get_user(self, headers=None):
55
- user_name = headers.get('userName')
66
+ user_name = headers.get("userName")
56
67
  try:
57
- user = self.get_object('users', data={'email': user_name}, headers=headers)
68
+ user = self.get_object("users", data={"email": user_name}, headers=headers)
58
69
  return user
59
70
  except Exception as e:
60
71
  raise e
@@ -62,9 +73,11 @@ class RemoteRepository:
62
73
  def get_object(self, table, keys=None, data=None, headers=None):
63
74
  params = self.get_params(data, keys)
64
75
  try:
65
- response = requests.get(self.url_repository + 'single/' + table, params=params, headers=headers)
76
+ response = requests.get(
77
+ self.url_repository + "single/" + table, params=params, headers=headers
78
+ )
66
79
  if response.status_code < 200 or response.status_code > 299:
67
- raise Exception(f'Error getting data: {response.text}')
80
+ raise Exception(f"Error getting data: {response.text}")
68
81
  return response.json()
69
82
  except Exception as e:
70
83
  raise e
@@ -75,21 +88,23 @@ class RemoteRepository:
75
88
  def get_objects(self, table, keys=None, data=None, headers=None):
76
89
  params = self.get_params(data, keys)
77
90
  try:
78
- response = requests.get(self.url_repository + table, params=params, headers=headers)
91
+ response = requests.get(
92
+ self.url_repository + table, params=params, headers=headers
93
+ )
79
94
  if response.status_code < 200 or response.status_code > 299:
80
- raise Exception(f'Error getting data: {response.text}')
95
+ raise Exception(f"Error getting data: {response.text}")
81
96
  return response.json()
82
97
  except Exception as e:
83
98
  raise e
84
99
 
85
100
  def execute_select(self, select, headers=None):
86
- command = {
87
- 'command': select
88
- }
101
+ command = {"command": select}
89
102
  try:
90
- response = requests.post(self.url_repository + "command/select", headers=headers, json=command)
103
+ response = requests.post(
104
+ self.url_repository + "command/select", headers=headers, json=command
105
+ )
91
106
  if response.status_code < 200 or response.status_code > 299:
92
- raise Exception(f'Error getting data: {response.text}')
107
+ raise Exception(f"Error getting data: {response.text}")
93
108
  return response.json()
94
109
  except Exception as e:
95
110
  raise e
@@ -29,17 +29,17 @@ class Starter:
29
29
  pass
30
30
  SchedulerService.init(10)
31
31
  self.cors = CORS(self.app)
32
- self.app.config['CORS_HEADERS'] = 'Content-Type'
33
- self.config = Configs(os.getenv('PROFILE', 'dev'))
32
+ self.app.config["CORS_HEADERS"] = "Content-Type"
33
+ self.config = Configs(os.getenv("PROFILE", "dev"))
34
34
  self.remote_repository = RemoteRepository()
35
35
  self.http_repository = HttpRepository(remote_repository=self.remote_repository)
36
- self.interceptor = Interceptor(self.app, self.http_repository, save_request=save_request)
36
+ self.interceptor = Interceptor(
37
+ self.app, self.http_repository, save_request=save_request
38
+ )
37
39
  self.metrics = PrometheusMetrics(
38
40
  self.app,
39
- group_by='endpoint',
40
- default_labels={
41
- 'application': Version.get_app_name()
42
- }
41
+ group_by="endpoint",
42
+ default_labels={"application": Version.get_app_name()},
43
43
  )
44
44
 
45
45
  def get_remote_repository(self):
@@ -56,7 +56,8 @@ class Starter:
56
56
  self.app,
57
57
  application_name=Version.get_app_name(),
58
58
  application_version=Version.get_version(),
59
- swagger_destination_path='swagger.yaml'
59
+ swagger_destination_path="swagger.yaml",
60
+ )
61
+ self.app.run(
62
+ host="0.0.0.0", port=Configs.get_env_variable(Config.PORT, default=5000)
60
63
  )
61
- self.app.run(host='0.0.0.0',
62
- port=Configs.get_env_variable(Config.PORT, default=5000))
@@ -14,11 +14,12 @@ from csctracker_py_core.utils.version import Version
14
14
  class CustomJsonFormatter(jsonlogger.JsonFormatter):
15
15
  def add_fields(self, log_record, record, message_dict):
16
16
  super().add_fields(log_record, record, message_dict)
17
- log_record['requestId'] = RequestInfo.get_request_id()
18
- log_record['appName'] = Version.get_app_name()
19
- log_record['appVersion'] = Version.get_version()
20
- log_record['name'] = \
17
+ log_record["requestId"] = RequestInfo.get_request_id()
18
+ log_record["appName"] = Version.get_app_name()
19
+ log_record["appVersion"] = Version.get_version()
20
+ log_record["name"] = (
21
21
  f"{os.path.splitext(os.path.basename(record.pathname))[0]}.{record.funcName}:{record.lineno}"
22
+ )
22
23
 
23
24
 
24
25
  class Encoder(json.JSONEncoder):
@@ -29,12 +30,14 @@ class Encoder(json.JSONEncoder):
29
30
 
30
31
  class Configs:
31
32
  def __init__(self, env):
32
- log = logging.getLogger('werkzeug')
33
+ log = logging.getLogger("werkzeug")
33
34
  log.setLevel(logging.ERROR)
34
35
 
35
36
  self.logger = logging.getLogger()
36
37
  self.logger.setLevel(Configs.log_level())
37
- formatter = CustomJsonFormatter('%(levelname)s %(name)s %(requestId)s %(appName)s %(message)s')
38
+ formatter = CustomJsonFormatter(
39
+ "%(levelname)s %(name)s %(requestId)s %(appName)s %(message)s"
40
+ )
38
41
  json_handler = logging.StreamHandler()
39
42
  json_handler.setFormatter(formatter)
40
43
  self.logger.addHandler(json_handler)
@@ -47,8 +50,8 @@ class Configs:
47
50
 
48
51
  def load_env(self):
49
52
  env_file = f"config/{self.env}.env"
50
- os.environ['APPLICATION_VERSION'] = Version.get_version()
51
- os.environ['APPLICATION_NAME'] = Version.get_app_name()
53
+ os.environ["APPLICATION_VERSION"] = Version.get_version()
54
+ os.environ["APPLICATION_NAME"] = Version.get_app_name()
52
55
  load_dotenv(env_file)
53
56
 
54
57
  @staticmethod
@@ -76,17 +79,17 @@ class Configs:
76
79
  variable = Configs.get_env_variable(Config.LOG_LEVEL)
77
80
 
78
81
  if variable is None:
79
- variable = 'INFO'
82
+ variable = "INFO"
80
83
  variable = variable.upper()
81
- if variable == 'DEBUG':
84
+ if variable == "DEBUG":
82
85
  return logging.DEBUG
83
- elif variable == 'INFO':
86
+ elif variable == "INFO":
84
87
  return logging.INFO
85
- elif variable == 'WARNING':
88
+ elif variable == "WARNING":
86
89
  return logging.WARNING
87
- elif variable == 'ERROR':
90
+ elif variable == "ERROR":
88
91
  return logging.ERROR
89
- elif variable == 'CRITICAL':
92
+ elif variable == "CRITICAL":
90
93
  return logging.CRITICAL
91
94
  else:
92
95
  return logging.INFO
@@ -36,25 +36,25 @@ class Interceptor:
36
36
  now = time.time()
37
37
  duration = round(now - g.start, 2)
38
38
  log_entry = {
39
- 'method': request.method,
40
- 'path': request.path,
41
- 'status': response.status_code,
42
- 'args': dict(request.args),
43
- 'duration': f'{duration}s',
44
- 'date': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now)),
45
- 'requestId': g.correlation_id,
46
- 'appName': Version.get_app_name(),
47
- 'appVersion': Version.get_version(),
39
+ "method": request.method,
40
+ "path": request.path,
41
+ "status": response.status_code,
42
+ "args": dict(request.args),
43
+ "duration": f"{duration}s",
44
+ "date": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(now)),
45
+ "requestId": g.correlation_id,
46
+ "appName": Version.get_app_name(),
47
+ "appVersion": Version.get_version(),
48
48
  }
49
- if Configs.get_env_variable(Config.LOG_RESPONSE_BODY) == 'True':
50
- log_entry['response'] = response.get_json()
49
+ if Configs.get_env_variable(Config.LOG_RESPONSE_BODY) == "True":
50
+ log_entry["response"] = response.get_json()
51
51
 
52
- if Configs.get_env_variable(Config.LOG_REQUEST_BODY) == 'True':
52
+ if Configs.get_env_variable(Config.LOG_REQUEST_BODY) == "True":
53
53
  try:
54
- log_entry['request'] = request.get_json()
54
+ log_entry["request"] = request.get_json()
55
55
  except Exception:
56
56
  pass
57
- if request.path in ['/metrics', '/health']:
57
+ if request.path in ["/metrics", "/health"]:
58
58
  self.logger.debug(log_entry)
59
59
  else:
60
60
  self.logger.info(log_entry)
@@ -65,10 +65,10 @@ class Interceptor:
65
65
  def save_request_info(self, request_, response, path):
66
66
  try:
67
67
  data = response.get_data()
68
- decoded_data = data.decode('utf-8', 'ignore')
68
+ decoded_data = data.decode("utf-8", "ignore")
69
69
  headers_ = Utils.conv_keys_to_lower(dict(request_.headers))
70
- if 'x-correlation-id' not in headers_:
71
- headers_['x-correlation-id'] = RequestInfo.get_request_id()
70
+ if "x-correlation-id" not in headers_:
71
+ headers_["x-correlation-id"] = RequestInfo.get_request_id()
72
72
  request_info_ = {
73
73
  "path": path,
74
74
  "method": request_.method,
@@ -76,22 +76,24 @@ class Interceptor:
76
76
  "parameters": str(dict(request_.args)),
77
77
  "body": request_.get_data(as_text=True),
78
78
  "response": decoded_data,
79
- "success": 'S' if response.status_code < 400 else 'F',
79
+ "success": "S" if response.status_code < 400 else "F",
80
80
  "duration": round(time.time() - g.start, 2),
81
81
  "request_id": RequestInfo.get_request_id(),
82
- "date_time": datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'),
82
+ "date_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"),
83
83
  }
84
84
  headers = {
85
85
  "Content-Type": "application/json",
86
86
  "Authorization": f"Bearer {Configs.get_env_variable(Config.API_TOKEN)}",
87
- "x-correlation-id": RequestInfo.get_request_id()
87
+ "x-correlation-id": RequestInfo.get_request_id(),
88
88
  }
89
89
  args_ = {
90
- 'url': f"{Configs.get_env_variable(Config.URL_BFF)}rabbit/requests",
91
- 'body': request_info_,
92
- 'headers': headers
90
+ "url": f"{Configs.get_env_variable(Config.URL_BFF)}rabbit/requests",
91
+ "body": request_info_,
92
+ "headers": headers,
93
93
  }
94
- SchedulerService.put_in_queue(self.http_repository.post, args=args_, priority=True)
94
+ SchedulerService.put_in_queue(
95
+ self.http_repository.post, args=args_, priority=True
96
+ )
95
97
  except Exception as e:
96
98
  logging.getLogger().error(f"Error: {str(e)}")
97
99
  pass
@@ -15,7 +15,7 @@ class RequestInfo:
15
15
  except Exception:
16
16
  try:
17
17
  thread = threading.current_thread()
18
- request_id_ = thread.__getattribute__('correlation_id')
18
+ request_id_ = thread.__getattribute__("correlation_id")
19
19
  except Exception:
20
20
  if create_new:
21
21
  request_id_ = f"{Version.get_app_name()}-{str(uuid.uuid4())}"
@@ -26,4 +26,6 @@ class RequestInfo:
26
26
 
27
27
  @staticmethod
28
28
  def get_correlation_id():
29
- return request.headers.get('x-correlation-id', f"{Version.get_app_name()}-{str(uuid.uuid4())}")
29
+ return request.headers.get(
30
+ "x-correlation-id", f"{Version.get_app_name()}-{str(uuid.uuid4())}"
31
+ )
@@ -20,9 +20,9 @@ class Encoder(json.JSONEncoder):
20
20
  if isinstance(obj, decimal.Decimal):
21
21
  return float(obj)
22
22
  if isinstance(obj, datetime.datetime):
23
- return obj.strftime('%Y-%m-%d %H:%M:%S.%f')
23
+ return obj.strftime("%Y-%m-%d %H:%M:%S.%f")
24
24
  if isinstance(obj, datetime.date):
25
- return obj.strftime('%Y-%m-%d')
25
+ return obj.strftime("%Y-%m-%d")
26
26
 
27
27
 
28
28
  class Utils:
@@ -46,7 +46,7 @@ class Utils:
46
46
 
47
47
  @staticmethod
48
48
  def read_file(file_name):
49
- file_dir = os.path.dirname(os.path.realpath('__file__'))
49
+ file_dir = os.path.dirname(os.path.realpath("__file__"))
50
50
  file_name = os.path.join(file_dir, file_name)
51
51
  file_handle = open(file_name)
52
52
  content = file_handle.read()
@@ -76,7 +76,9 @@ class Utils:
76
76
  return dt_string.strftime(format)
77
77
 
78
78
  @staticmethod
79
- def get_format_date_time_in_tz(dt_string, format, original_tz='America/Sao_Paulo', new_tz='UTC'):
79
+ def get_format_date_time_in_tz(
80
+ dt_string, format, original_tz="America/Sao_Paulo", new_tz="UTC"
81
+ ):
80
82
  dt_obj = datetime.strptime(dt_string, format)
81
83
 
82
84
  original_tz_ = pytz.timezone(original_tz)
@@ -100,15 +102,17 @@ class Utils:
100
102
  "text": msg,
101
103
  "data": json_,
102
104
  "app": Version.get_app_name(),
103
- "operation": operation
105
+ "operation": operation,
104
106
  }
105
107
 
106
108
  if from_ is not None:
107
- message['from'] = from_
109
+ message["from"] = from_
108
110
 
109
111
  response = requests.post(
110
112
  f"{Configs.get_env_variable(Config.URL_BFF, default='http://bff:8080/')}notify-sync/message",
111
- headers=headers, json=message)
113
+ headers=headers,
114
+ json=message,
115
+ )
112
116
  if response.status_code != 200:
113
117
  logging.getLogger().info(response.status_code)
114
118
  pass
@@ -127,7 +131,7 @@ class Utils:
127
131
  return str(calendar.monthrange(int(year), int(month))[1])
128
132
 
129
133
  @staticmethod
130
- def fill_left(value, size, fill_char='0'):
134
+ def fill_left(value, size, fill_char="0"):
131
135
  return str(value).rjust(size, fill_char)
132
136
 
133
137
  @staticmethod
@@ -4,12 +4,12 @@ import logging
4
4
  class Version:
5
5
  @staticmethod
6
6
  def get_version():
7
- return open('version.txt', 'r').read().strip()
7
+ return open("version.txt", "r").read().strip()
8
8
 
9
9
  @staticmethod
10
10
  def get_app_name():
11
11
  try:
12
- return open('app_name.txt', 'r').read().strip()
12
+ return open("app_name.txt", "r").read().strip()
13
13
  except Exception as e:
14
14
  logging.getLogger().error(e)
15
- return 'no_app_name'
15
+ return "no_app_name"
@@ -0,0 +1,157 @@
1
+ Metadata-Version: 2.4
2
+ Name: csctracker-py-core
3
+ Version: 26.7.7
4
+ Summary: A base library for microservices with Flask, JSON logging, and Prometheus telemetry.
5
+ Home-page: https://github.com/krlsedu/CscTrackerPyCore
6
+ Author: Carlos Eduardo
7
+ License: MIT
8
+ Project-URL: Bug Tracker, https://github.com/krlsedu/CscTrackerPyCore/issues
9
+ Project-URL: Source Code, https://github.com/krlsedu/CscTrackerPyCore
10
+ Keywords: microservices,flask,json-logging,prometheus,telemetry,swagger,openapi,background-jobs,scheduler,observability,http-client,middleware
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Information Technology
14
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
15
+ Classifier: Topic :: System :: Logging
16
+ Classifier: Topic :: System :: Monitoring
17
+ Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware
18
+ Classifier: License :: OSI Approved :: MIT License
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.9
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Operating System :: OS Independent
25
+ Requires-Python: >=3.9
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Requires-Dist: csctracker-queue-scheduler==24.6.1
29
+ Requires-Dist: flask~=3.0.0
30
+ Requires-Dist: python-json-logger
31
+ Requires-Dist: python-dotenv~=1.0.0
32
+ Requires-Dist: requests~=2.32.0
33
+ Requires-Dist: beautifulsoup4==4.10.0
34
+ Requires-Dist: flask-cors~=3.0.7
35
+ Requires-Dist: prometheus-flask-exporter==0.22.4
36
+ Requires-Dist: flask-swagger-init==23.52.4
37
+ Requires-Dist: pytz~=2023.3.post1
38
+ Dynamic: author
39
+ Dynamic: classifier
40
+ Dynamic: description
41
+ Dynamic: description-content-type
42
+ Dynamic: home-page
43
+ Dynamic: keywords
44
+ Dynamic: license
45
+ Dynamic: license-file
46
+ Dynamic: project-url
47
+ Dynamic: requires-dist
48
+ Dynamic: requires-python
49
+ Dynamic: summary
50
+
51
+ # CscTrackerPyCore
52
+
53
+ [![PyPI version](https://img.shields.io/pypi/v/csctracker-py-core.svg)](https://pypi.org/project/csctracker-py-core/)
54
+ [![Python versions](https://img.shields.io/pypi/pyversions/csctracker-py-core.svg)](https://pypi.org/project/csctracker-py-core/)
55
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
56
+ [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
57
+
58
+ CscTrackerPyCore é uma biblioteca Python base desenvolvida para padronizar e acelerar o desenvolvimento de microserviços. Ela oferece integração nativa com Flask, fornecendo recursos essenciais como logging estruturado em JSON, telemetria com Prometheus, documentação automática via Swagger e gerenciamento de tarefas agendadas.
59
+
60
+ ## Principais Funcionalidades
61
+
62
+ - **Starter Facilitado**: Inicialização rápida de aplicações Flask com suporte a CORS e tratamento de variáveis de ambiente.
63
+ - **Logging Estruturado**: Formatação automática de logs em JSON com inclusão de `requestId`, `appName` e `appVersion` para melhor rastreabilidade.
64
+ - **Observabilidade**:
65
+ - Integração nativa com **Prometheus** para coleta de métricas de endpoints.
66
+ - **Interceptor de Requisições**: Registro detalhado de chamadas HTTP (método, path, status, duração) com opção de persistência remota para auditoria.
67
+ - **Documentação Automática**: Geração de especificação **Swagger (OpenAPI)** simplificada.
68
+ - **Processamento em Background**: Integração com `csctracker-queue-scheduler` para execução de tarefas assíncronas e agendadas.
69
+ - **Repositórios Remotos**: Abstração para comunicação entre serviços via HTTP com tratamento de headers e correlação.
70
+
71
+ ## Requisitos
72
+
73
+ - Python 3.9+
74
+ - Flask
75
+ - Flask-CORS
76
+ - Prometheus Flask Exporter
77
+ - Flask Swagger Generator
78
+ - Python JSON Logger
79
+ - Python Dotenv
80
+
81
+ ## Instalação
82
+
83
+ As dependências podem ser instaladas via `pip`:
84
+
85
+ ```bash
86
+ pip install csctracker-py-core
87
+ ```
88
+
89
+ Ou via `requirements.txt`:
90
+
91
+ ```bash
92
+ pip install -r requirements.txt
93
+ ```
94
+
95
+ ## Configuração
96
+
97
+ A biblioteca é configurada principalmente via variáveis de ambiente, suportando arquivos `.env` localizados na pasta `config/` (ex: `config/dev.env`).
98
+
99
+ ### Variáveis de Ambiente Suportadas
100
+
101
+ | Variável | Descrição | Exemplo |
102
+ | :--- | :--- | :--- |
103
+ | `PROFILE` | Perfil de configuração (define o arquivo .env) | `dev` |
104
+ | `PORT` | Porta de execução do servidor Flask | `5000` |
105
+ | `LOG_LEVEL` | Nível de detalhamento do log | `INFO`, `DEBUG` |
106
+ | `LOG_REQUEST_BODY` | Se `True`, inclui o corpo da requisição nos logs | `True` |
107
+ | `LOG_RESPONSE_BODY` | Se `True`, inclui o corpo da resposta nos logs | `False` |
108
+ | `URL_BFF` | URL base para persistência de logs de requisição | `http://api-gateway/` |
109
+ | `API_TOKEN` | Token de autorização para chamadas externas | `seu_token_aqui` |
110
+ | `DEBUG` | Ativa o modo debug do Flask se definido como `1` | `0` |
111
+
112
+ ## Uso Didático
113
+
114
+ ### 1. Inicialização do `Starter`
115
+
116
+ A classe `Starter` centraliza a configuração do Flask.
117
+
118
+ ```python
119
+ from csctracker_py_core.starter import Starter
120
+
121
+ # Inicializa o starter (static_folder define a pasta de arquivos estáticos)
122
+ # save_request=True ativa a persistência remota de logs de requisição
123
+ starter = Starter(save_request=False)
124
+
125
+ # Obtém a instância do Flask configurada
126
+ app = starter.get_app()
127
+
128
+ @app.route('/')
129
+ def hello():
130
+ return {"message": "CscTrackerPyCore is running!"}
131
+
132
+ if __name__ == '__main__':
133
+ starter.start()
134
+ ```
135
+
136
+ ### 2. Logging e Interceptação
137
+
138
+ Uma vez iniciado o `Starter`, todos os logs do sistema usarão o formato JSON e as requisições serão interceptadas automaticamente para gerar telemetria.
139
+
140
+ ### 3. Acesso aos Repositórios
141
+
142
+ ```python
143
+ # Acesso ao repositório HTTP para chamadas externas padronizadas
144
+ http_repo = starter.get_http_repository()
145
+ ```
146
+
147
+ ## Estrutura do Projeto
148
+
149
+ - `Starter`: Orquestrador principal que configura Flask, CORS, Métricas e Swagger.
150
+ - `Configs`: Gerencia o carregamento de variáveis de ambiente e a configuração do logger JSON.
151
+ - `Interceptor`: Middleware Flask que captura dados de performance e logs de entrada/saída.
152
+ - `HttpRepository`: Facilita requisições HTTP externas com injeção de headers de segurança e rastreio.
153
+ - `RequestInfo`: Utilitário para gerenciar IDs de correlação (Correlation IDs) entre threads.
154
+
155
+ ## Licença
156
+
157
+ Este projeto está sob a licença MIT. Consulte o arquivo `LICENSE` para mais detalhes.
@@ -0,0 +1,59 @@
1
+ import setuptools
2
+ from version import get_version
3
+
4
+ VERSION = get_version()
5
+
6
+ with open("README.md", "r", encoding="utf-8") as fh:
7
+ long_description = fh.read()
8
+
9
+ with open("requirements.txt") as f:
10
+ required = f.read().splitlines()
11
+
12
+ setuptools.setup(
13
+ name="csctracker-py-core",
14
+ version=VERSION,
15
+ license="MIT",
16
+ author="Carlos Eduardo",
17
+ description="A base library for microservices with Flask, JSON logging, and Prometheus telemetry.",
18
+ long_description=long_description,
19
+ long_description_content_type="text/markdown",
20
+ url="https://github.com/krlsedu/CscTrackerPyCore",
21
+ project_urls={
22
+ "Bug Tracker": "https://github.com/krlsedu/CscTrackerPyCore/issues",
23
+ "Source Code": "https://github.com/krlsedu/CscTrackerPyCore",
24
+ },
25
+ packages=setuptools.find_packages(exclude=["tests", "tests.*"]),
26
+ keywords=[
27
+ "microservices",
28
+ "flask",
29
+ "json-logging",
30
+ "prometheus",
31
+ "telemetry",
32
+ "swagger",
33
+ "openapi",
34
+ "background-jobs",
35
+ "scheduler",
36
+ "observability",
37
+ "http-client",
38
+ "middleware"
39
+ ],
40
+ classifiers=[
41
+ "Development Status :: 4 - Beta",
42
+ "Intended Audience :: Developers",
43
+ "Intended Audience :: Information Technology",
44
+ "Topic :: Software Development :: Libraries :: Python Modules",
45
+ "Topic :: System :: Logging",
46
+ "Topic :: System :: Monitoring",
47
+ "Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware",
48
+ "License :: OSI Approved :: MIT License",
49
+ "Programming Language :: Python :: 3",
50
+ "Programming Language :: Python :: 3.9",
51
+ "Programming Language :: Python :: 3.10",
52
+ "Programming Language :: Python :: 3.11",
53
+ "Programming Language :: Python :: 3.12",
54
+ "Operating System :: OS Independent",
55
+ ],
56
+ install_requires=required,
57
+ python_requires=">=3.9",
58
+ include_package_data=True,
59
+ )
@@ -1,57 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: csctracker-py-core
3
- Version: 26.7.4
4
- Summary: A library for handle scheduled jobs.
5
- Home-page: https://github.com/krlsedu/CscTrackerPyCore.git
6
- Author: Carlos Eduardo
7
- License: MIT
8
- Keywords: queue,scheduled,scheduler
9
- Classifier: Intended Audience :: Developers
10
- Classifier: Programming Language :: Python :: 3
11
- Classifier: Programming Language :: Python :: 3.9
12
- Classifier: Topic :: Software Development
13
- Requires-Python: >=3
14
- Description-Content-Type: text/markdown
15
- License-File: LICENSE
16
- Requires-Dist: csctracker-queue-scheduler==24.6.1
17
- Requires-Dist: flask~=3.0.0
18
- Requires-Dist: python-json-logger
19
- Requires-Dist: python-dotenv~=1.0.0
20
- Requires-Dist: requests~=2.32.0
21
- Requires-Dist: beautifulsoup4==4.10.0
22
- Requires-Dist: flask-cors~=3.0.7
23
- Requires-Dist: prometheus-flask-exporter==0.22.4
24
- Requires-Dist: flask-swagger-init==23.52.4
25
- Requires-Dist: pytz~=2023.3.post1
26
- Dynamic: author
27
- Dynamic: classifier
28
- Dynamic: description
29
- Dynamic: description-content-type
30
- Dynamic: home-page
31
- Dynamic: keywords
32
- Dynamic: license
33
- Dynamic: license-file
34
- Dynamic: requires-dist
35
- Dynamic: requires-python
36
- Dynamic: summary
37
-
38
- # CscTrackerPyCore
39
-
40
- ## Key Features
41
-
42
- ## Documentation and Examples
43
-
44
- COMING SOON
45
-
46
- ## Testing
47
-
48
- Currently, this project does not have automated tests. They may be added in the future as needed.
49
-
50
- ## Contributing
51
-
52
- If you would like to contribute to this project, feel free to fork the repository, make your changes, and propose a pull
53
- request.
54
-
55
- ## License
56
-
57
- This project is under the MIT license. Please refer to the `LICENSE` file for more details.
@@ -1,20 +0,0 @@
1
- # CscTrackerPyCore
2
-
3
- ## Key Features
4
-
5
- ## Documentation and Examples
6
-
7
- COMING SOON
8
-
9
- ## Testing
10
-
11
- Currently, this project does not have automated tests. They may be added in the future as needed.
12
-
13
- ## Contributing
14
-
15
- If you would like to contribute to this project, feel free to fork the repository, make your changes, and propose a pull
16
- request.
17
-
18
- ## License
19
-
20
- This project is under the MIT license. Please refer to the `LICENSE` file for more details.
@@ -1,57 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: csctracker-py-core
3
- Version: 26.7.4
4
- Summary: A library for handle scheduled jobs.
5
- Home-page: https://github.com/krlsedu/CscTrackerPyCore.git
6
- Author: Carlos Eduardo
7
- License: MIT
8
- Keywords: queue,scheduled,scheduler
9
- Classifier: Intended Audience :: Developers
10
- Classifier: Programming Language :: Python :: 3
11
- Classifier: Programming Language :: Python :: 3.9
12
- Classifier: Topic :: Software Development
13
- Requires-Python: >=3
14
- Description-Content-Type: text/markdown
15
- License-File: LICENSE
16
- Requires-Dist: csctracker-queue-scheduler==24.6.1
17
- Requires-Dist: flask~=3.0.0
18
- Requires-Dist: python-json-logger
19
- Requires-Dist: python-dotenv~=1.0.0
20
- Requires-Dist: requests~=2.32.0
21
- Requires-Dist: beautifulsoup4==4.10.0
22
- Requires-Dist: flask-cors~=3.0.7
23
- Requires-Dist: prometheus-flask-exporter==0.22.4
24
- Requires-Dist: flask-swagger-init==23.52.4
25
- Requires-Dist: pytz~=2023.3.post1
26
- Dynamic: author
27
- Dynamic: classifier
28
- Dynamic: description
29
- Dynamic: description-content-type
30
- Dynamic: home-page
31
- Dynamic: keywords
32
- Dynamic: license
33
- Dynamic: license-file
34
- Dynamic: requires-dist
35
- Dynamic: requires-python
36
- Dynamic: summary
37
-
38
- # CscTrackerPyCore
39
-
40
- ## Key Features
41
-
42
- ## Documentation and Examples
43
-
44
- COMING SOON
45
-
46
- ## Testing
47
-
48
- Currently, this project does not have automated tests. They may be added in the future as needed.
49
-
50
- ## Contributing
51
-
52
- If you would like to contribute to this project, feel free to fork the repository, make your changes, and propose a pull
53
- request.
54
-
55
- ## License
56
-
57
- This project is under the MIT license. Please refer to the `LICENSE` file for more details.
@@ -1,32 +0,0 @@
1
- import setuptools
2
- from version import get_version
3
-
4
- VERSION = get_version()
5
-
6
- with open("README.md", "r") as fh:
7
- long_description = fh.read()
8
-
9
- with open('requirements.txt') as f:
10
- required = f.read().splitlines()
11
-
12
- setuptools.setup(
13
- name="csctracker-py-core",
14
- version=VERSION,
15
- license="MIT",
16
- author="Carlos Eduardo",
17
- description="A library for handle scheduled jobs.",
18
- long_description=long_description,
19
- long_description_content_type="text/markdown",
20
- url="https://github.com/krlsedu/CscTrackerPyCore.git",
21
- packages=setuptools.find_packages(exclude=['tests', 'tests.*']),
22
- keywords=['queue', 'scheduled', 'scheduler'],
23
- classifiers=[
24
- "Intended Audience :: Developers",
25
- 'Programming Language :: Python :: 3',
26
- 'Programming Language :: Python :: 3.9',
27
- "Topic :: Software Development",
28
- ],
29
- install_requires=required,
30
- python_requires='>=3',
31
- include_package_data=True,
32
- )