Skip to content

Commit 3d5daa2

Browse files
refactor(app): Updating the folders's structure and adding support language documentation.
1 parent 6c87b02 commit 3d5daa2

31 files changed

+1287
-32
lines changed

.env-sample

Lines changed: 0 additions & 5 deletions
This file was deleted.

.env.example

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
DB_USER=user
2+
DB_PASSWORD=password
3+
DB_HOST=domain
4+
DB_PORT=port
5+
DB_SERVICE_NAME=service_name

README.md

Lines changed: 48 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,78 @@
1+
🌍 [Leia em Português](README.pt-BR.md)
2+
13
# Crud
24

3-
Crud com métodos de inserção, atualização, captura, remoção de dados de um banco de dados oracle utilizando a biblioteca requests em python
5+
Crud for manipulations in oracle database with methods of inserting, updating, capturing and removing data. using the `requests` library in python.
6+
7+
# Technologies Used
8+
9+
- `requests` - Communication with api.
10+
- `pytest` - Testing.
11+
- `oracledb` - Connect with oracle database.
12+
- `python-dotenv` - Load environment variables.
13+
- `flask` - Development of api.
14+
- `flask_cors` - Api CORS configuration.
15+
16+
# Features
417

5-
## Instalação
18+
- Manipulation of data from a database: Methods of inserting, updating, creating, and removing data using requests.
19+
- Simple and intuitive interface: Simple and entuitive command-line interface for handling a database.
20+
- Dynamic interface, being able to manipulate the table you want!
621

7-
1. **Clone o repositório:**
22+
## Steps to install and run
23+
24+
1. Clone the Repository:
825

926
```bash
10-
git clone https://github.com/felipeclarindo/crud
27+
git clone https://github.com/felipeclarindo/crud-cli.git
1128
```
1229

13-
2. **Navegue até o diretorio do projeto:**
30+
2. Enter directory:
1431

1532
```bash
16-
cd crud
33+
cd crud-cli
1734
```
1835

19-
3. **Rode a API**
36+
3. Create `Virtual Environment`:
2037

2138
```bash
22-
python ./database/api.py
39+
python -m venv .venv
2340
```
2441

25-
4. **Execute o Programa**
42+
4. Enable `Virtual Environment` by running the `.bat` file in `.venv/Scripts/activate.bat`.
43+
44+
5. Install dependencies:
2645

2746
```bash
28-
python ./main.py
47+
pip install - r requirements.txt
2948
```
3049

31-
# Funcionalidades
50+
6. Run api server:
51+
52+
```bash
53+
python src/api/server.py
54+
```
55+
56+
7. Run the application:
57+
58+
```bash
59+
python src/main.py
60+
```
3261

33-
- **Manipulação de dados de uma database**: Métodos de inserção, atualização, criação e remoção de dados utilizando requests.
34-
- **Interface simples e intuitiva**: Interface em linha de comando simples e entuitiva para manipulação de um banco de dados.
35-
- **Dinamico**: Interface dinamica, podendo manipular a tabela que desejar!
62+
8. Interact with the menu interface and perform the desired manipulation in the database.
3663

37-
## Contribuição
64+
## Contribution
3865

39-
Contribuições são bem-vindas! Se você tiver sugestões de melhorias, sinta-se à vontade para abrir uma issue ou enviar um pull request.
66+
Contributions are welcome! If you have suggestions for improvements, feel free to open an issue or submit a pull request.
4067

41-
## Autor
68+
## Author
4269

4370
**Felipe Clarindo**
4471

45-
- [LinkedIn](https://www.linkedin.com/in/felipe-clarindo-934578289/)
46-
- [Instagram](https://www.instagram.com/lipethegoat)
72+
- [LinkedIn](https://www.linkedin.com/in/felipeclarindo)
73+
- [Instagram](https://www.instagram.com/lipethecoder)
4774
- [GitHub](https://github.com/felipeclarindo)
4875

49-
## Licença
76+
## License
5077

51-
Este projeto está licenciado sob a [GNU Affero License](https://www.gnu.org/licenses/agpl-3.0.html).
78+
This project is licensed under the [GNU Affero License](https://www.gnu.org/licenses/agpl-3.0.html).

README.pt-BR.md

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
🌍 [Read in English](README.md)
2+
3+
# Crud
4+
5+
Crud para manipulações em banco de dados oracle com métodos de inserção, atualização, captura e remoção de dados. utilizando a biblioteca `requests` em python.
6+
7+
# Tecnologias Utilizadas
8+
9+
- `requests` - Comunicação com a api.
10+
- `pytest` - Realizaçaõ dos testes.
11+
- `oracledb` - Conectar com a database da oracle.
12+
- `python-dotenv` - Carregar variaveis de ambientes.
13+
- `flask` - Desenvolvimento da api.
14+
- `flask_cors` - Configuração do CORS da api.
15+
16+
# Funcionalidades
17+
18+
- Manipulação de dados de uma database: Métodos de inserção, atualização, criação e remoção de dados utilizando requests.
19+
- Interface simples e intuitiva: Interface em linha de comando simples e entuitiva para manipulação de um banco de dados.
20+
- Dinamico: Interface dinamica, podendo manipular a tabela que desejar!
21+
22+
## Passos para instalação e execução
23+
24+
1. Clone o repositório:
25+
26+
```bash
27+
git clone https://github.com/felipeclarindo/crud-cli.git
28+
```
29+
30+
2. Entre no diretório:
31+
32+
```bash
33+
cd crud-cli
34+
```
35+
36+
3. Crie o `Ambiente Virtual`:
37+
38+
```bash
39+
python -m venv .venv
40+
```
41+
42+
4. Ative o `Ambiente Virtual` executando o arquivo `.bat` em `.venv/Scripts/activate.bat`.
43+
44+
5. Instale as dependências:
45+
46+
```bash
47+
pip install -r requirements.txt
48+
```
49+
50+
6. Execute o servidor da api:
51+
52+
```bash
53+
python src/api/server.py
54+
```
55+
56+
7. Execute a aplicação:
57+
58+
```bash
59+
python src/main.py
60+
```
61+
62+
8. Interaja com a interface do menu e realize a manipulação desejada no banco de dados.
63+
64+
## Contribuição
65+
66+
Contribuições são bem-vindas! Se você tiver sugestões de melhorias, sinta-se à vontade para abrir uma issue ou enviar um pull request.
67+
68+
## Autor
69+
70+
Felipe Clarindo
71+
72+
- [LinkedIn](https://www.linkedin.com/in/felipe-clarindo-934578289/)
73+
- [Instagram](https://www.instagram.com/lipethegoat)
74+
- [GitHub](https://github.com/felipeclarindo)
75+
76+
## Licença
77+
78+
Este projeto está licenciado sob a [GNU Affero License](https://www.gnu.org/licenses/agpl-3.0.html).
File renamed without changes.

api/api.py

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
from flask import Flask, request, jsonify
2+
from flask_cors import CORS
3+
from database.models import Crud
4+
5+
# Inicializando a aplicação
6+
app = Flask(__name__)
7+
CORS(app) # Habilitando CORS
8+
9+
# Rota principal com informações da API
10+
@app.route("/api", methods=["GET"])
11+
def index():
12+
return jsonify({
13+
"name": "Crud Api",
14+
"endpoints": {
15+
"/api/table": {
16+
"methods": {
17+
"POST": "post new data",
18+
"PATCH": "update single field",
19+
"DELETE": "delete data",
20+
"GET": "get all data or data by id",
21+
}
22+
}
23+
},
24+
"libraries": ["flask", "flask_cors"],
25+
"developer": "felipeclarindo",
26+
"github": "https://github.com/felipeclarindo"
27+
}), 200
28+
29+
# Rota para inserção de dados
30+
@app.route("/api/table", methods=["POST"])
31+
def post():
32+
data = request.json
33+
if not data or not isinstance(data, dict):
34+
return jsonify({"message": "Dados inválidos ou ausentes."}), 400
35+
36+
crud = Crud()
37+
response = crud.post(data)
38+
return jsonify(response), (201 if response["status"] == "success" else 400)
39+
40+
# Rota para pegar todos os dados
41+
@app.route("/api/table", methods=["GET"])
42+
def get_all():
43+
table = request.json.get("table")
44+
if not table:
45+
return jsonify({"message": "Parâmetro 'table' é obrigatório."}), 400
46+
47+
crud = Crud()
48+
response = crud.get(table)
49+
return jsonify(response), (200 if response["status"] == "success" else 400)
50+
51+
# Rota para pegar dados por ID específico
52+
@app.route("/api/table/<int:id>", methods=["GET"])
53+
def get_with_id(id: int):
54+
table = request.json.get("table")
55+
if not table:
56+
return jsonify({"message": "Parâmetro 'table' é obrigatório."}), 400
57+
58+
crud = Crud()
59+
response = crud.get_with_id(table, id)
60+
return jsonify(response), (200 if response["status"] == "success" else 400)
61+
62+
# Rota para atualização de um único campo de um dado
63+
@app.route("/api/table/<int:id>", methods=["PATCH"])
64+
def patch(id: int):
65+
data = request.json
66+
if not data:
67+
return jsonify({"message": "Dados não encontrados."}), 400
68+
69+
table = data.get("table")
70+
column = data.get("column")
71+
value = data.get("value")
72+
73+
if not table or not column or not value:
74+
return jsonify({"message": "Parâmetros obrigatórios ausentes."}), 400
75+
76+
crud = Crud()
77+
response = crud.patch(table, id, column, value)
78+
return jsonify(response), (200 if response["status"] == "success" else 400)
79+
80+
# Rota para deletar dado pelo ID
81+
@app.route("/api/table/<int:id>", methods=["DELETE"])
82+
def delete(id: int):
83+
table = request.json.get("table") if request.json else None
84+
if not table:
85+
return jsonify({"message": "Parâmetro 'table' é obrigatório."}), 400
86+
87+
crud = Crud()
88+
response = crud.delete(table, id)
89+
return jsonify(response), (200 if response["status"] == "success" else 400)
90+
91+
92+
if __name__ == "__main__":
93+
app.run(debug=True, port=3000)
File renamed without changes.

api/database/config.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from dotenv import load_dotenv
2+
from time import sleep
3+
import oracledb
4+
import os
5+
6+
# Carrega as variaveis de ambiente do arquivo .env
7+
load_dotenv()
8+
9+
10+
def connect():
11+
try:
12+
# Dados para conexão
13+
username = os.getenv("DB_USER")
14+
password = os.getenv("DB_PASSWORD")
15+
host = os.getenv("DB_HOST")
16+
port = os.getenv("DB_PORT")
17+
service_name = os.getenv("DB_SERVICE_NAME")
18+
19+
# Criando conexão
20+
dsn = f"{username}/{password}@{host}:{port}/{service_name}"
21+
print(f"Conectando ao banco de dados em {host}:{port} como {username}...")
22+
sleep(1)
23+
connection = oracledb.connect(dsn)
24+
if connection:
25+
print("Conexão feita com sucesso!")
26+
return connection
27+
except Exception as e:
28+
print(f"Falha na conexão: {e}.")
29+
return None
30+

0 commit comments

Comments
 (0)