Skip to content

Commit

Permalink
Add processing of data, favicon
Browse files Browse the repository at this point in the history
  • Loading branch information
krystofkomanec committed Nov 7, 2024
1 parent 9acd243 commit 5c59065
Show file tree
Hide file tree
Showing 8 changed files with 96 additions and 11 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -161,3 +161,6 @@ cython_debug/
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
.idea/
.env

# Web app output
output
20 changes: 19 additions & 1 deletion src/dsw_seed_maker/api.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import contextlib
import json
import logging
import pathlib

Expand All @@ -10,7 +11,7 @@
from .config import Config
from .consts import NICE_NAME, VERSION
from .models import ExampleRequestDTO, ExampleResponseDTO
from .logic import example_logic, list_logic
from .logic import example_logic, list_logic, process_input

LOG = logging.getLogger('uvicorn.error')
ROOT = pathlib.Path(__file__).parent
Expand Down Expand Up @@ -142,6 +143,23 @@ async def get_documents():
raise fastapi.HTTPException(status_code=500, detail='Could not fetch documents')


router = fastapi.APIRouter()

@router.post("/api/process")
async def process_data(data: dict):
try:
input_data = json.loads(data["data"]) # Parse the input JSON data
output_dir = "output" # Define your output directory
process_input(input_data, output_dir) # Call the function with the data
return fastapi.responses.JSONResponse(content={"status": "success", "message": "Processing completed successfully"})
except Exception as e:
return fastapi.responses.JSONResponse(status_code=400, content={"status": "error", "message": str(e)})

# Make sure to include the router in the FastAPI app
app.include_router(router)



@app.post('/api/seed-package', response_class=fastapi.responses.JSONResponse)
async def post_seed():
# TODO: implement
Expand Down
45 changes: 44 additions & 1 deletion src/dsw_seed_maker/logic.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,9 @@ def download_file_logic(file_name: str, target_path: str) -> bool:
def create_recipe_file(output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
with open("recipe_tmp.json", 'r') as template_recipe:
script_dir = pathlib.Path(__file__).parent
recipe_file_path = script_dir / 'recipe_tmp.json'
with open(recipe_file_path, 'r') as template_recipe:
data = template_recipe.read()
with open(os.path.join(output_dir, 'recipe.json'), 'w') as recipe:
recipe.write(data)
Expand Down Expand Up @@ -291,12 +293,47 @@ def handle_id(data, db, file, resource_type):
else:
print("User not found in database")

def log_and_write_query(resource, resource_type, recipe_file, db, file_dir):
try:
# Generate insert query
insert_query = generate_insert_query(resource[0], resource_tables[resource_type])
print(f"Generated insert query: {insert_query}")

# Write to recipe file
write_seed_files_db(recipe_file, insert_query)

# Ensure recipe_file is a path string, not a file object
if isinstance(recipe_file, str):
file_path = recipe_file
else:
# If recipe_file is a file object, get the file path
file_path = recipe_file.name # .name gives the file path for file objects

# Check if the file exists and is writable
if not os.path.exists(file_path): # Check if the file exists
print(f"Error: The file path {file_path} does not exist.")
return
elif not os.access(file_path, os.W_OK): # Check if the file is writable
print(f"Error: {file_path} is not writable.")
return

# Open the file in append mode
with open(file_path, 'a') as f:
print(f"Writing query to {file_path}")
f.write(insert_query + '\n')
print(f"Successfully wrote query to {file_path}")

except Exception as e:
print(f"Error writing query to file: {e}")


def handle_users(input_data, db, recipe_file, resource_type, output_dir):
query = "SELECT * FROM {resource_type} WHERE uuid = '{uuid}'".format(uuid=input_data['uuid'], resource_type=resource_tables[resource_type])
resource = db.execute_query(query)
if len(resource) == 1:
insert_query = generate_insert_query(resource[0], resource_tables[resource_type])
write_seed_files_db(recipe_file, insert_query)
log_and_write_query(resource, resource_type, recipe_file, db, output_dir)
else:
print("User not found in database/more than one record with that ID")

Expand All @@ -306,6 +343,7 @@ def handle_projects(input_data, db, recipe_file, resource_type, output_dir):
if len(resource) == 1:
insert_query = generate_insert_query(resource[0], resource_tables[resource_type])
write_seed_files_db(recipe_file, insert_query)
log_and_write_query(resource, resource_type, recipe_file, db, output_dir)
else:
print("User not found in database")

Expand All @@ -315,6 +353,7 @@ def handle_documents(input_data, db, recipe_file, resource_type, output_dir):
if len(resource) == 1:
insert_query = generate_insert_query(resource[0], resource_tables[resource_type])
write_seed_files_db(recipe_file, insert_query)
log_and_write_query(resource, resource_type, recipe_file, db, output_dir)
else:
print("User not found in database")

Expand All @@ -324,6 +363,7 @@ def handle_project_importers(input_data, db, recipe_file, resource_type, output_
if len(resource) == 1:
insert_query = generate_insert_query(resource[0], resource_tables[resource_type])
write_seed_files_db(recipe_file, insert_query)
log_and_write_query(resource, resource_type, recipe_file, db, output_dir)
else:
print("Project Importer not found in database")

Expand All @@ -335,6 +375,7 @@ def handle_knowledge_models(input_data, db, recipe_file, resource_type, output_d
print(resource)
insert_query = generate_insert_query(resource[0], resource_tables[resource_type])
write_seed_files_db(recipe_file, insert_query)
log_and_write_query(resource, resource_type, recipe_file, db, output_dir)
else:
print("User not found in database")

Expand All @@ -346,6 +387,7 @@ def handle_locales(input_data, db, recipe_file, resource_type, output_dir):
if len(resource) == 1:
insert_query = generate_insert_query(resource[0], resource_tables[resource_type])
write_seed_files_db(recipe_file, insert_query)
log_and_write_query(resource, resource_type, recipe_file, db, output_dir)
s3_locales = download_file_logic("locales/" + input_data['id'], output_dir + "/app" + "/locales/" + input_data['name'] )
if s3_locales:
print("File downloaded")
Expand All @@ -360,6 +402,7 @@ def handle_document_templates(input_data, db, recipe_file, resource_type, output
if len(resource) == 1:
insert_query = generate_insert_query(resource[0], resource_tables[resource_type])
write_seed_files_db(recipe_file, insert_query)
log_and_write_query(resource, resource_type, recipe_file, db, output_dir)
else:
print("User not found in database")

Expand Down
8 changes: 0 additions & 8 deletions src/dsw_seed_maker/static/css/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -89,20 +89,12 @@ h1 {
color: #fff;
}

.btn-primary:hover {
background-color: darken(var(--primary-color), 10%); /* Slightly darker on hover */
}

.btn-secondary {
background-color: var(--secondary-color); /* Secondary color for secondary buttons */
color: #fff;
border: none;
}

.btn-secondary:hover {
background-color: darken(var(--secondary-color), 10%); /* Slightly darker on hover */
}

/* Textarea Styles */
textarea {
border-radius: 8px;
Expand Down
Binary file added src/dsw_seed_maker/static/favicon.ico
Binary file not shown.
26 changes: 26 additions & 0 deletions src/dsw_seed_maker/static/js/script.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
jQuery(document).ready(function ($) {
const $btn_copy = $('#btn-copy');
const $btn_list = $('#btn-list');
const $btn_process = $('#btn-process'); // Add reference to the "Process" button
const $input_search = $('#input-search');
const $output_search = $('#output-search');

// Function to fetch data from the API
function fetchData() {
const userInput = $input_search.val();
$.ajax({
Expand All @@ -22,7 +24,31 @@ jQuery(document).ready(function ($) {
});
}

// Function to call the process API endpoint
function processData() {
const inputData = $output_search.val(); // Get the current content of the output_search (editable textbox)

$.ajax({
url: `${ROOT_PATH}/api/process`, // Call the new endpoint
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ data: inputData }), // Send the input data
success: function (response) {
const processedData = JSON.stringify(response, null, 2);
$output_search.val(processedData); // Display the processed data in the textbox
$output_search.prop('readonly', false);
},
error: function (xhr, status, error) {
const errorMessage = `Error processing data: ${error}`;
$output_search.val(errorMessage);
$output_search.prop('readonly', true);
}
});
}

// Button click event handlers
$btn_list.click(fetchData);
$btn_process.click(processData); // Attach processData to the "Process" button click

$input_search.keypress(function (event) {
if (event.key === "Enter") {
Expand Down
3 changes: 2 additions & 1 deletion src/dsw_seed_maker/templates/index.html.j2
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@

<div class="response-section">
<h3>Response:</h3>
<textarea id="output-search" class="form-control" rows="10" readonly></textarea>
<textarea id="output-search" class="form-control" rows="15" readonly></textarea>
<button id="btn-copy" class="btn btn-secondary mt-2">Copy to Clipboard</button>
<button id="btn-process" class="btn btn-secondary mt-2">Process</button>
</div>

<footer class="footer mt-4">
Expand Down
2 changes: 2 additions & 0 deletions src/dsw_seed_maker/templates/layout.html.j2
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<link href="static/css/style.css" rel="stylesheet">

<link rel="icon" href="/static/favicon.ico" type="image/x-icon">

<script>
const ROOT_PATH = "{{ ROOT_PATH }}"
</script>
Expand Down

0 comments on commit 5c59065

Please sign in to comment.