generate_api.py
1 2 from datetime import datetime 3 from revolve.data_types import State 4 from revolve.utils import log, read_python_code_template, save_python_code, copy_template_files_to_source_folder 5 from revolve.utils import create_schemas_endpoint 6 from revolve.utils_git import commit_and_push_changes 7 8 def generate_api(state:State): 9 send = state.get("send") 10 log("Started", send) 11 resources = state.get("resources", []) 12 added_sources = [] 13 if resources: 14 api_template = read_python_code_template("api.py") 15 for resource in resources: 16 api_routes = resource["api_route"] 17 for route in api_routes: 18 uri = route["uri"] 19 resource_object = route["resource_object"] 20 module_name = resource["resource_file_name"].replace(".py","") 21 library_name = resource_object.replace("()","") 22 if module_name+"."+library_name not in added_sources: 23 api_template = api_template.replace("###IMPORTS###", f"###IMPORTS###\nfrom {module_name} import {library_name}") 24 added_sources.append(module_name+"."+library_name) 25 if uri+"."+resource_object not in added_sources: 26 api_template = api_template.replace("###ENDPOINTS###", f"""###ENDPOINTS###\napp.add_route("{uri}", {resource_object})""") 27 added_sources.append(uri+"."+resource_object) 28 29 save_python_code( 30 api_template, 31 "api.py" 32 ) 33 34 template_files = [ 35 "static.py", 36 "db_utils.py", 37 "cors.py" 38 ] 39 copy_template_files_to_source_folder(template_files) 40 41 create_schemas_endpoint(state) 42 commit_and_push_changes( 43 message="Codes and api generated." 44 ) 45 46 47 new_trace = { 48 "node_name": "generate_api", 49 "node_type": "process", 50 "node_input": state["resources"], 51 "node_output": api_template, 52 "trace_timestamp": datetime.now(), 53 "description": "APIs are generated. You can take a look by clicking Start under Server Controls (on the left). I am still going to run tests." 54 } 55 56 log("APIs are generated. You can take a look by clicking Start under Server Controls (on the left). I am still going to run tests.", send=send, level="notification") 57 58 return { 59 "trace": [new_trace] 60 }