Added support for regenerate the modules for direct loading in bottle

This commit is contained in:
Antonio de la Rosa 2016-03-18 03:41:20 +01:00
parent 3f1942cbfb
commit 11dd833f08
6 changed files with 259 additions and 96 deletions

102
paramecio/create_module.py Normal file
View file

@ -0,0 +1,102 @@
#!/usr/bin/python3
import traceback
import argparse
import os,sys
import shutil
import getpass
from pathlib import Path
from settings import config
from importlib import import_module
def start():
parser=argparse.ArgumentParser(description='A tool for create new modules for paramecio')
parser.add_argument('--path', help='The path where the new paramecio module is located', required=True)
args=parser.parse_args()
workdir=os.path.dirname(os.path.abspath(__file__))
# Create directory
path=Path('modules/'+args.path)
try:
path.mkdir(0o755, True)
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')
try:
shutil.copy(workdir+'/examples/index.py', 'modules/'+args.path)
except:
print('Error: cannot copy controller example. Check if you have permissions')
exit(1)
# Regenerate modules
regenerate_modules_config()
def regenerate_modules_config():
print("Regenerating modules configuration...")
modules=[]
modules.append("#!/usr/bin/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 ')
for controller in dir_controllers:
if controller.find('.py')!=-1 and controller.find('__init__')==-1:
controller_py=controller.replace('.py', '')
modules.append(controller_py)
#load(module+'.'+controller_py)
modules.append("\n\n")
#add_func_static_module(controller_base)
except:
print("Exception in user code:")
print("-"*60)
traceback.print_exc(file=sys.stdout)
print("-"*60)
exit(1)
f=open('./settings/modules.py', 'w')
f.write("".join(modules))
f.close()
if __name__=="__main__":
start()

View file

@ -0,0 +1,46 @@
from paramecio.cromosoma.webmodel import PhangoField
import json
class DictField(PhangoField):
def __init__(self, name, field_type, required=False):
super().__init__(name, required)
self.field_type=field_type
def check(self, value):
if type(value).__name__=='str':
try:
value=json.loads(value)
except json.JSONDecodeError:
value={}
self.error=True
self.txt_error='Sorry, the json array is invalid'
elif type(value).__name__!='dict':
value={}
self.error=True
self.txt_error='Sorry, the json array is invalid'
for k,v in enumerate(value):
value[k]=self.field_type.check(v)
final_value=json.dumps(value)
final_value=super().check(final_value)
return final_value
def get_type_sql(self):
return 'TEXT NOT NULL DEFAULT ""'
def show_formatted(self, value):
return ", ".join(value)

View file

@ -0,0 +1,12 @@
from paramecio.citoplasma.mtemplates import ptemplate
from paramecio.citoplasma.urls import make_url
from bottle import route, request
from settings import config
t=ptemplate(__file__)
@route('/example')
def home():
return "Hello World!!"

View file

@ -1,8 +1,6 @@
#!/usr/bin/python3
from paramecio.index import create_app, run_app
app=create_app()
from paramecio.index import app, run_app
if __name__ == "__main__":
run_app(app)

View file

@ -1,108 +1,113 @@
import os, sys, traceback, inspect
from importlib import import_module
from bottle import route, get, post, run, default_app, abort, request, static_file
from settings import config
from bottle import route, get, post, run, default_app, abort, request, static_file, load
from settings import config, modules
from beaker.middleware import SessionMiddleware
#Prepare links for static.
#WARNING: only use this feature in development, not in production.
def create_app():
#def create_app():
arr_module_path={}
arr_module_path={}
if config.yes_static==True:
if config.yes_static==True:
@route('/media/<filename:path>')
def send_static(filename):
return static_file(filename, root='themes/'+config.theme+'/media/')
@route('/media/<filename:path>')
def send_static(filename):
return static_file(filename, root='themes/'+config.theme+'/media/')
def add_func_static_module(module):
def add_func_static_module(module):
@route('/mediafrom/<module>/<filename:path>')
def send_static_module(module, filename):
@route('/mediafrom/<module>/<filename:path>')
def send_static_module(module, filename):
path_module=arr_module_path[module]+'/media/'
path_module=arr_module_path[module]+'/media/'
file_path_module=path_module+filename
file_path_module=path_module+filename
path='themes/'+config.theme+'/media/'+module
path='themes/'+config.theme+'/media/'+module
file_path=path+filename
file_path=path+filename
if os.path.isfile(file_path):
return static_file(filename, root=path)
if os.path.isfile(file_path):
return static_file(filename, root=path)
else:
return static_file(filename, root=path_module)
else:
else:
return static_file(filename, root=path_module)
else:
def add_func_static_module(module):
pass
def add_func_static_module(module):
pass
routes={}
routes={}
module_loaded=None
module_loaded=None
#Import modules to load
#Import modules to load
for module in config.modules:
for module in config.modules:
try:
module=module.replace('.', '/')
controller_path=import_module(module)
controller_base=os.path.basename(module)
controller_base=os.path.dirname(controller_path.__file__)
add_func_static_module(controller_base)
base_module=module.split('.')[-1]
"""
try:
arr_module_path[base_module]=controller_base
controller_path=load(module)
dir_controllers=os.listdir(controller_base)
controller_base=os.path.dirname(controller_path.__file__)
for controller in dir_controllers:
base_module=module.split('.')[-1]
if controller.find('.py')!=-1 and controller.find('__init__')==-1:
arr_module_path[base_module]=controller_base
controller_py=controller.replace('.py', '')
dir_controllers=os.listdir(controller_base)
import_module(module+'.'+controller_py)
for controller in dir_controllers:
add_func_static_module(controller_base)
if controller.find('.py')!=-1 and controller.find('__init__')==-1:
except:
controller_py=controller.replace('.py', '')
print("Exception in user code:")
print("-"*60)
traceback.print_exc(file=sys.stdout)
print("-"*60)
load(module+'.'+controller_py)
#exit()
add_func_static_module(controller_base)
#Prepare ssl
except:
if config.ssl==True:
print("Exception in user code:")
print("-"*60)
traceback.print_exc(file=sys.stdout)
print("-"*60)
"""
#exit()
from citoplasma.gunicornssl import GunicornServerSSL
#Prepare ssl
GunicornServerSSL.cert_pem=config.cert_pem
GunicornServerSSL.privkey_pem=config.privkey_pem
if config.ssl==True:
config.server_used=GunicornServerSSL
from citoplasma.gunicornssl import GunicornServerSSL
#Prepare app
GunicornServerSSL.cert_pem=config.cert_pem
GunicornServerSSL.privkey_pem=config.privkey_pem
app = application = default_app()
config.server_used=GunicornServerSSL
if config.session_enabled==True:
#Create dir for sessions
#Prepare app
if not os.path.isdir(config.session_opts['session.data_dir']):
os.makedirs(config.session_opts['session.data_dir'], 0o700, True)
app = application = default_app()
app = SessionMiddleware(app, config.session_opts, environ_key=config.cookie_name)
if config.session_enabled==True:
#Create dir for sessions
return app
if not os.path.isdir(config.session_opts['session.data_dir']):
os.makedirs(config.session_opts['session.data_dir'], 0o700, True)
app = SessionMiddleware(app, config.session_opts, environ_key=config.cookie_name)
def run_app(app):