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 itsdangerous import JSONWebSignatureSerializer
from cuchulu.libraries.keyutils import create_key_encrypt, create_key_encrypt_256, create_key from cuchulu.libraries.keyutils import create_key_encrypt, create_key_encrypt_256, create_key
from cuchulu.wsgiapp import app 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 #from cuchulu.libraries.sessions import after_session
modules_pass=False modules_pass=False
@ -83,7 +91,10 @@ def prepare_app():
""" """
app_mounts={} 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(): for key_app, added_app in config.apps.items():
controller_path=import_module(added_app[0]) controller_path=import_module(added_app[0])
@ -118,7 +129,7 @@ def prepare_app():
app.mount(k_app, v_app) app.mount(k_app, v_app)
elif k_app!='': elif k_app!='':
app.merge(v_app) app.merge(v_app)
set_timezone() set_timezone()
if error_reporting: if error_reporting:
@ -255,9 +266,5 @@ def error_handler_500(e):
app.error(code=500, callback=error_handler_500) app.error(code=500, callback=error_handler_500)
def run_app(app): 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)
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()

View file

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

View file

@ -6,9 +6,21 @@ import os,sys
import shutil import shutil
import getpass import getpass
from pathlib import Path from pathlib import Path
from settings import config
from importlib import import_module 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(): def start():
"""Module for create new modules for cuchulu """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=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() args=parser.parse_args()
@ -24,137 +36,33 @@ def start():
# Create directory # Create directory
path=Path('modules/'+args.path) real_path=os.path.basename(slugify(args.folder))
path=Path('modules/'+real_path)
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 path.mkdir(0o755, True)
#f=open('modules/'+args.path+'/index.py', 'w') #open('modules/'+args.path+'/__init__.py', 'a').close()
with open('modules/'+real_path+'/__init__.py', 'a') as f:
name_module=os.path.basename(args.path) f.write("from bottle import Bottle\n\n")
f.write("{}_app=Bottle()\n\n".format(real_path, real_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...')
except:
print('Cannot update configuration, you need add the new module by hand')
# Reload config
#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: with open('modules/'+real_path+'/app.py', 'w') as f:
controller_py=controller.replace('.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))
arr_controllers.append(controller_py) f.write("def {}_home():\n".format(real_path, real_path))
f.write(" return {'hello': 'world'}")
#load(module+'.'+controller_py)
modules.append(", ".join(arr_controllers)) with open('settings/modules.py', 'a') as f:
modules.append("\n\n")
#add_func_static_module(controller_base)
except: if not real_path in modules.extra_apps:
#modules.extra_apps[real_path]=['modules.{}'.format(real_path), '{}_app'.format(real_path), '/']
print("Exception in user code:") f.write("extra_apps['{}']=['modules.{}', '{}_app', '/']".format(real_path, real_path, real_path))
print("-"*60)
traceback.print_exc(file=sys.stdout) print('Created the new module. Please, reload the WSGI server if not reload automatically and go to url /'+real_path)
print("-"*60)
exit(1)
with open('./settings/modules.py', 'w') as f:
f.write("".join(modules))
if __name__=="__main__": if __name__=="__main__":
start() start()

View file

@ -1,6 +1,6 @@
#!/usr/bin/env python3 #!/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] [project.scripts]
cuchulu = "cuchulu.console:start" cuchulu = "cuchulu.console:start"
cuchuludb = "cuchulu.libraries.db.dbadmin:start" cuchuludb = "cuchulu.libraries.db.dbadmin:start"
cuchulucm = "cuchulu.scripts.create_module:start" cuchulucm = "cuchulu.create_module:start"
[tool.pytest.ini_options] [tool.pytest.ini_options]
testpaths = ["tests"] testpaths = ["tests"]