Fix for create new modules

This commit is contained in:
Antonio de la Rosa 2025-11-30 01:40:34 +01:00
parent be21a6eca2
commit c6935845c3
5 changed files with 57 additions and 141 deletions

View file

@ -9,6 +9,14 @@ from cuchulu.libraries.datetime import set_timezone
#from itsdangerous import JSONWebSignatureSerializer
from cuchulu.libraries.keyutils import create_key_encrypt, create_key_encrypt_256, create_key
from cuchulu.wsgiapp import app
try:
from settings import modules as modules_external
except:
class modules_external:
extra_apps={}
#from cuchulu.libraries.sessions import after_session
modules_pass=False
@ -84,6 +92,9 @@ def prepare_app():
app_mounts={}
if len(modules_external.extra_apps)>0:
config.apps=config.apps | modules_external.extra_apps
for key_app, added_app in config.apps.items():
controller_path=import_module(added_app[0])
@ -255,9 +266,5 @@ def error_handler_500(e):
app.error(code=500, callback=error_handler_500)
def run_app(app):
if config.server_used!='cherrypy':
run(app=app, host=config.host, server=config.server_used, port=config.port, debug=config.debug, reloader=config.reloader)
else:
from cuchulu.cherry import run_cherrypy_server
run_cherrypy_server()
run(app=app, host=config.host, server=config.server_used, port=config.port, debug=config.debug, reloader=config.reloader)

View file

@ -79,7 +79,7 @@ def start():
except:
print('Error: cannot copy the file app.py. Check if exists and if you have permissions for this task')
"""
try:
shutil.copy(workdir+'/frontend/padmin.py', args.path+'/padmin.py')
@ -113,6 +113,7 @@ def start():
print('Error: cannot copy the file create_module.py. Check if exists and if you have permissions for this task')
"""
try:
shutil.copy(workdir+'/settings/modules.py', path_settings+'/modules.py')
@ -120,7 +121,7 @@ def start():
except:
print('Error: cannot copy the file modules.py. Check if exists and if you have permissions for this task')
"""
if args.symlink==True:
try:

View file

@ -6,9 +6,21 @@ import os,sys
import shutil
import getpass
from pathlib import Path
from settings import config
from importlib import import_module
import re
from cuchulu.libraries.slugify import slugify
from settings import modules
import json
sys.path.insert(0, os.path.realpath('.'))
try:
from settings import config
except:
pass
def start():
"""Module for create new modules for cuchulu
@ -16,7 +28,7 @@ def start():
parser=argparse.ArgumentParser(description='A tool for create new modules for cuchulu')
parser.add_argument('--path', help='The path where the new cuchulu module is located', required=True)
parser.add_argument('--folder', help='The folder where the new cuchulu module is located', required=True)
args=parser.parse_args()
@ -24,137 +36,33 @@ def start():
# Create directory
path=Path('modules/'+args.path)
real_path=os.path.basename(slugify(args.folder))
try:
path.mkdir(0o755, True)
open('modules/'+args.path+'/__init__.py', 'a').close()
except:
print('Error: cannot create the directory. Check if exists and if you have permissions')
exit(1)
#Create base controller file
#f=open('modules/'+args.path+'/index.py', 'w')
name_module=os.path.basename(args.path)
try:
shutil.copy(workdir+'/examples/app.py', 'modules/'+args.path)
with open('modules/'+args.path+'/app.py') as f:
app_file=f.read()
app_file=app_file.replace('/example', '/'+name_module)
with open('modules/'+args.path+'/app.py', 'w') as f:
f.write(app_file)
pass
except:
print('Error: cannot copy controller example. Check if you have permissions')
exit(1)
# Edit config.py
#module_final='modules.'+name_module
module_final=f"'{name_module}': ['modules.{name_module}', '', '']"
try:
with open('./settings/config.py') as f:
#modules_final='\''+'\', \''.join(final_modules)+'\''
p=re.compile(r"^apps=\{(.*)\}$")
#config_file=p.sub(r"modules=[\1, "+modules_final+"]", "modules=['cuchulu.modules.welcome', 'cuchulu.modules.admin', 'cuchulu.modules.lang', 'modules.pastafari', 'modules.monit', 'modules.example']")
final_config=''
for line in f:
if p.match(line):
line=p.sub(r"apps={\1, "+module_final+"}", line)
final_config+=line
with open('./settings/config.py', 'w') as f:
f.write(final_config)
print('Updated configuration for add new modules...')
path=Path('modules/'+real_path)
except:
path.mkdir(0o755, True)
print('Cannot update configuration, you need add the new module by hand')
#open('modules/'+args.path+'/__init__.py', 'a').close()
with open('modules/'+real_path+'/__init__.py', 'a') as f:
f.write("from bottle import Bottle\n\n")
f.write("{}_app=Bottle()\n\n".format(real_path, real_path))
# Reload config
with open('modules/'+real_path+'/app.py', 'w') as f:
#config.modules.append(module_final)
# Regenerate modules
#regenerate_modules_config()
def regenerate_modules_config():
print("Regenerating modules configuration...")
modules=[]
modules.append("#!/usr/bin/env python3\n\n")
modules.append("list_modules=[]\n\n")
for module in config.modules:
try:
controller_path=import_module(module)
controller_base=os.path.dirname(controller_path.__file__)
base_module=module.split('.')[-1]
dir_controllers=os.listdir(controller_base)
modules.append('from '+module+' import ')
arr_controllers=[]
for controller in dir_controllers:
if controller.find('.py')!=-1 and controller.find('_')==-1:
controller_py=controller.replace('.py', '')
arr_controllers.append(controller_py)
#load(module+'.'+controller_py)
f.write("from modules.{} import {}_app\n\n".format(real_path, real_path))
f.write("@{}_app.route('/{}')\n\n".format(real_path, real_path))
f.write("def {}_home():\n".format(real_path, real_path))
f.write(" return {'hello': 'world'}")
modules.append(", ".join(arr_controllers))
with open('settings/modules.py', 'a') as f:
modules.append("\n\n")
if not real_path in modules.extra_apps:
#modules.extra_apps[real_path]=['modules.{}'.format(real_path), '{}_app'.format(real_path), '/']
f.write("extra_apps['{}']=['modules.{}', '{}_app', '/']".format(real_path, real_path, real_path))
#add_func_static_module(controller_base)
except:
print("Exception in user code:")
print("-"*60)
traceback.print_exc(file=sys.stdout)
print("-"*60)
exit(1)
with open('./settings/modules.py', 'w') as f:
f.write("".join(modules))
print('Created the new module. Please, reload the WSGI server if not reload automatically and go to url /'+real_path)
if __name__=="__main__":
start()

View file

@ -1,6 +1,6 @@
#!/usr/bin/env python3
list_modules=[]
# This a internal configuration, probably, this file will be rewrite when you create a new module with cuchulucm script.
from cuchulu.modules.welcome import index
extra_apps={}

View file

@ -47,7 +47,7 @@ Documentation = "https://docs.cuchulu.com/cuchulu/"
[project.scripts]
cuchulu = "cuchulu.console:start"
cuchuludb = "cuchulu.libraries.db.dbadmin:start"
cuchulucm = "cuchulu.scripts.create_module:start"
cuchulucm = "cuchulu.create_module:start"
[tool.pytest.ini_options]
testpaths = ["tests"]