Multiple fixes for go to most pythonic way

This commit is contained in:
Antonio de la Rosa 2016-05-23 05:26:50 +02:00
parent a2e8c937f7
commit dd4cd73785
9 changed files with 131 additions and 50 deletions

View file

@ -9,6 +9,7 @@ from paramecio.citoplasma.sessions import get_session
from paramecio.cromosoma.formsutils import csrf_token
from settings import config
from os import path
from collections import OrderedDict
# Preparing envs for views of modules, and views of
@ -24,26 +25,61 @@ template = env.get_template('mytemplate.html')
#ptemplate.clean_header_cache()
#pass
class ptemplate:
template_context=None
# A simple method used in internal things of paramecio
show_basic_template=True
"""
class Environment:
def __init__(self, module, cache_enabled=True, cache_impl='', cache_args={}):
self.cache_enable=cache_enabled
self.cache_impl=cache_impl
self.cache_args=cache_args
self.module_directory="./tmp/modules"
"""
def env_theme(module, cache_enabled=True, cache_impl='', cache_args={}, module_directory="./tmp/modules"):
ext=module[len(module)-3:]
if ext=='.py':
module=path.dirname(module)
standard_templates=path.dirname(__file__)+'/templates'
module_templates=module+'/templates'
theme_templates='themes/'+config.theme+'/templates'
search_folders=[theme_templates, module_templates, standard_templates]
#if self.inject_folder is not None:
#search_folders.insert(1, self.inject_folder+'/templates')
#Standard templates
#print(standard_templates)
return TemplateLookup(directories=search_folders, default_filters=['h'], input_encoding='utf-8', encoding_errors='replace', cache_enabled=cache_enabled, cache_impl=cache_impl, cache_args=cache_args, module_directory=module_directory)
class PTemplate:
def __init__(self, environment):
# A simple method used in internal things of paramecio
self.show_basic_template=True
"""
ext=module[len(module)-3:]
if ext=='.py':
module=path.dirname(module)
"""
self.autoescape_ext=('html', 'htm', 'xml', 'phtml')
"""
self.cache_enabled=cache_enabled
self.cache_impl=cache_impl
@ -51,6 +87,7 @@ class ptemplate:
self.cache_args=cache_args
self.module_directory="./tmp/modules"
"""
self.inject_folder=None
@ -91,7 +128,7 @@ class ptemplate:
self.filters['show_flash_message']=self.headerhtml.show_flash_message
self.env=self.env_theme(module)
self.env=environment
#self.auto_reload=True
@ -112,7 +149,7 @@ class ptemplate:
ext = template_name.rsplit('.', 1)[1]
return ext in self.autoescape_ext
"""
def env_theme(self, module):
standard_templates=path.dirname(__file__)+'/templates'
@ -133,7 +170,8 @@ class ptemplate:
#, cache_enabled=self.cache_enabled, cache_impl=self.cache_impl, cache_args=self.cache_args
#return Environment(autoescape=self.guess_autoescape, auto_reload=True, loader=FileSystemLoader([theme_templates, module_templates]))
"""
def load_templates(self, template_files):
for template_file in template_files:
@ -168,9 +206,9 @@ class HeaderHTML:
self.css=[]
self.js=[]
self.header=[]
self.cache_header={}
self.css_local={}
self.js_local={}
self.cache_header=OrderedDict()
self.css_local=OrderedDict()
self.js_local=OrderedDict()
def header_home(self):
@ -192,7 +230,7 @@ class HeaderHTML:
final_js.append('<script language="Javascript" src="'+make_media_url_module('js/'+js, module)+'"></script>')
self.js=[]
self.js_local={}
self.js_local=OrderedDict()
return "\n".join(final_js)
@ -210,7 +248,7 @@ class HeaderHTML:
final_css.append('<link href="'+make_media_url_module('css/'+css, module)+'" rel="stylesheet" type="text/css"/>')
self.css=[]
self.css_local={}
self.css_local=OrderedDict()
return "\n".join(final_css)
@ -284,4 +322,4 @@ def set_flash_message(self, message):
s['flash']=message
standard_t=ptemplate(__file__)
#standard_t=ptemplate(__file__)

View file

@ -6,21 +6,23 @@ pymysql.install_as_MySQLdb()
class SqlClass:
connection={}
connection_method=''
def __init__(self):
self.error_connection=""
self.connection={}
self.error_connection=""
self.connected=False
self.connection_method=self.connect_to_db_sql
SqlClass.connection_method=self.connect_to_db_sql
def dummy_connect(self, connection, name_connection="default"):
pass
def connect_to_db(self, connection, name_connection="default"):
self.connection_method(connection, name_connection)
SqlClass.connection_method(connection, name_connection)
self.connection_method=self.dummy_connect
SqlClass.connection_method=self.dummy_connect
def connect_to_db_sql(self, connection, name_connection="default"):
@ -84,7 +86,7 @@ class SqlClass:
self.close(self.connection)
"""
"""
def close(self, name_connection="default"):
if self.connection[name_connection]:
@ -93,5 +95,5 @@ class SqlClass:
self.connection[name_connection]=False
pass
"""

View file

@ -3,6 +3,7 @@
import sys
import MySQLdb.cursors
import sqlalchemy.pool as pool
import traceback
class SqlClass:
@ -62,7 +63,7 @@ class SqlClass:
#with self.connection[name_connection].cursor(MySQLdb.cursors.DictCursor) as cursor:
cursor=self.connection[name_connection].cursor(MySQLdb.cursors.DictCursor)
try:
cursor.execute(sql_query, arguments)
@ -76,8 +77,8 @@ class SqlClass:
if hasattr(cursor, '_last_executed'):
sql_query=cursor._last_executed
self.error_connection="Error in query ||"+sql_query+"||: %s %s" % (e, v)
#, traceback.format_exc()
self.error_connection="Error in query ||%s||Values: %s" % (sql_query, str(arguments))
#return False
raise NameError(self.error_connection)

View file

@ -35,6 +35,29 @@ def pass_values_to_form(post, arr_form, yes_error=True):
arr_form[key].field.error=None
return arr_form
class CheckForm():
def __init__(self):
self.error=0
def check(self, post, arr_form):
for k in arr_form.keys():
post[k]=post.get(k, '')
if arr_form[k].field==None:
arr_form[k].field=corefields.CharField(k, 255, required=False)
post[k]=arr_form[k].field.check(post[k])
arr_form[k].txt_error=arr_form[k].field.txt_error
if arr_form[k].field.error==True and arr_form[k].required==True:
self.error+=1
return post, arr_form
def show_form(post, arr_form, t, yes_error=True, modelform_tpl='forms/modelform.phtml'):

View file

@ -83,6 +83,8 @@ class WebModel:
self.query_error=""
self.values_query=[]
self.conditions=["WHERE 1=1", []]
self.order_by="ORDER BY `"+self.name+"`.`id` ASC"
@ -198,9 +200,13 @@ class WebModel:
return False
sql="insert into `"+self.name+"` (`"+"`, `".join(fields)+"`) VALUES ("+", ".join(values)+")"
c=len(values)
cursor=self.sqlclass.query(sql, self.conditions[1], self.connection_id)
arr_str=['%s' for x in range(c)]
sql="insert into `"+self.name+"` (`"+"`, `".join(fields)+"`) VALUES ("+", ".join(arr_str)+")"
cursor=self.sqlclass.query(sql, values+self.conditions[1], self.connection_id)
if cursor.rowcount>0:
@ -245,7 +251,7 @@ class WebModel:
sql="update `"+self.name+"` SET "+", ".join(update_values)+" "+self.conditions[0]
cursor=self.sqlclass.query(sql, self.conditions[1], self.connection_id)
cursor=self.sqlclass.query(sql, values+self.conditions[1], self.connection_id)
if self.yes_reset_conditions:
self.reset_conditions()
@ -419,11 +425,9 @@ class WebModel:
return row
def select_a_row_where(self, fields_selected=[], raw_query=0):
def select_a_row_where(self, fields_selected=[], raw_query=0, begin=0):
if self.limit=='':
self.limit="limit 1"
self.limit="limit "+str(begin)+", 1"
cursor=self.select(fields_selected, raw_query)
@ -697,7 +701,7 @@ class WebModel:
error=False
if yes_update==True:
f_update=lambda field, value: "`"+field+"`="+value+""
f_update=lambda field, value: "`"+field+"`=%s"
else:
f_update=lambda field, value: ""
@ -745,11 +749,12 @@ class WebModel:
fields.append(k)
final_value=self.fields[k].quot_open+value+self.fields[k].quot_close
#final_value=self.fields[k].quot_open+value+self.fields[k].quot_close
#final_value=self.fields[k].quot_open+value+self.fields[k].quot_close
values.append(final_value)
values.append(value)
update_values.append(f_update(k, final_value))
update_values.append(f_update(k, value))
else:
self.num_errors+=1

View file

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

View file

@ -1,7 +1,7 @@
#!/usr/bin/python3
import traceback, sys
from paramecio.citoplasma.mtemplates import ptemplate
from paramecio.citoplasma.mtemplates import env_theme, PTemplate
from paramecio.modules.admin.models.admin import UserAdmin
from paramecio.citoplasma.i18n import load_lang, I18n
from paramecio.citoplasma.urls import make_url, add_get_parameters
@ -21,6 +21,7 @@ from collections import OrderedDict
from time import time
from paramecio.citoplasma.keyutils import create_key_encrypt
from os import path
import copy
#from citoplasma.login import LoginClass
# Check login
@ -31,14 +32,12 @@ key_encrypt=create_key_encrypt()
module_admin=path.dirname(__file__)
t=ptemplate(__file__)
env=env_theme(__file__)
def make_admin_url(url):
return make_url('%s/%s' % (config.admin_folder, url))
t.add_filter(make_admin_url)
@get('/'+config.admin_folder)
@get('/'+config.admin_folder+'/<module>')
@post('/'+config.admin_folder+'/<module>')
@ -48,7 +47,13 @@ def home(module='', submodule=''):
# A simple boolean used for show or not the code of admin module in standard template
connection=WebModel.connection()
ptemplate.show_basic_template=True
#Fix, make local variable
t=PTemplate(env)
t.add_filter(make_admin_url)
t.show_basic_template=True
if submodule!='':
module+='/'+submodule
@ -130,7 +135,7 @@ def home(module='', submodule=''):
content_index=new_module.admin(t=t, connection=connection)
if ptemplate.show_basic_template==True:
if t.show_basic_template==True:
return t.load_template('admin/content.html', title=menu[module][0], content_index=content_index, menu=menu, lang_selected=lang_selected, arr_i18n=I18n.dict_i18n)
else:

View file

@ -1,17 +1,21 @@
#!/usr/bin/python3
from paramecio.citoplasma.mtemplates import ptemplate
from paramecio.citoplasma.mtemplates import PTemplate, env_theme
from paramecio.citoplasma.urls import make_url
from bottle import route, request
from settings import config
t=ptemplate(__file__)
#t=ptemplate(__file__)
env=env_theme(__file__)
@route('/welcome')
def home():
t=PTemplate(env)
return t.load_template('welcome.html', title="Welcome to Paramecio!!!", content="The simple web framework writed in Python3!!!")
"""
@route('/welcome/<id:int>')
def page(id):
@ -21,6 +25,7 @@ def page(id):
def test(id):
return make_url('welcome/test/5', {'ohmygod': 'This is gooood', 'shutup':'Shut up!!'})
"""
if config.default_module=="welcome":