9 |
10 | URL | View Functions |
11 | {{for rule, methods, endpoint in urls:}}
12 | {{=rule}} {{=methods}} | {{=endpoint}} |
13 | {{pass}}
14 |
15 |
16 | {{end}}
--------------------------------------------------------------------------------
/uliweb/contrib/flashmessage/__init__.py:
--------------------------------------------------------------------------------
1 | def prepare_default_env(sender, env):
2 | env['get_flashed_messages'] = get_flashed_messages
3 | env['flash'] = flash
4 |
5 | def flash(message, category='success'):
6 | from uliweb import request
7 |
8 | request.session.setdefault('_flashed_messages', []).append((category, message))
9 |
10 | def get_flashed_messages():
11 | from uliweb import request
12 | if hasattr(request, 'session'):
13 | return request.session.pop('_flashed_messages', [])
14 | else:
15 | return []
--------------------------------------------------------------------------------
/uliweb/contrib/flashmessage/conf.py:
--------------------------------------------------------------------------------
1 | from uliweb.form import *
2 |
3 | #class ManageForm(Form):
4 | # debug_log = BooleanField(label='Debug Log:', key='ORM/DEBUG_LOG')
5 | # auto_create = BooleanField(label='Auto Create Table:', key='ORM/AUTO_CREATE')
6 | # connection = StringField(label='Database Connection String:', required=True, key='ORM/CONNECTION')
7 |
--------------------------------------------------------------------------------
/uliweb/contrib/flashmessage/config.ini:
--------------------------------------------------------------------------------
1 | [DEPENDS]
2 | REQUIRED_APPS = ['uliweb.contrib.session']
3 |
--------------------------------------------------------------------------------
/uliweb/contrib/flashmessage/info.ini:
--------------------------------------------------------------------------------
1 | [info]
2 | catalog = 'Representation Apps'
3 | title = 'Flashed Message App'
4 | description = 'You can use it to display flashed messages.'
5 | icon = ''
6 | author = 'limodou'
7 | version = '0.1'
8 | homepage = ''
9 |
--------------------------------------------------------------------------------
/uliweb/contrib/flashmessage/settings.ini:
--------------------------------------------------------------------------------
1 | [FUNCTIONS]
2 | flash = 'uliweb.contrib.flashmessage.flash'
3 |
4 | [BINDS]
5 | flashmessage.prepare_default_env = ('prepare_default_env', 'uliweb.contrib.flashmessage.prepare_default_env')
--------------------------------------------------------------------------------
/uliweb/contrib/flashmessage/templates/inc_show_flashes.html:
--------------------------------------------------------------------------------
1 | {{for category, message in get_flashed_messages():}}
2 | {{<
3 | {{pass}}
--------------------------------------------------------------------------------
/uliweb/contrib/flashmessage/templates/readme.txt:
--------------------------------------------------------------------------------
1 | This directory is used to store template files.
--------------------------------------------------------------------------------
/uliweb/contrib/form/__init__.py:
--------------------------------------------------------------------------------
1 | from uliweb import Finder, UliwebError, settings
2 | from uliweb.utils.common import import_attr
3 |
4 | validators = Finder('VALIDATORS')
5 |
6 | def get_form(formcls):
7 | """
8 | get form class according form class path or form class object
9 | """
10 | from uliweb.form import Form
11 | import inspect
12 |
13 | if inspect.isclass(formcls) and issubclass(formcls, Form):
14 | return formcls
15 | elif isinstance(formcls, (str, unicode)):
16 | path = settings.FORMS.get(formcls)
17 | if path:
18 | _cls = import_attr(path)
19 | return _cls
20 | else:
21 | raise UliwebError("Can't find formcls name %s in settings.FORMS" % formcls)
22 | else:
23 | raise UliwebError("formcls should be Form class object or string path format, but %r found!" % formcls)
24 |
25 | def startup_installed(sender):
26 | from uliweb import settings
27 | import uliweb.form.uliform as form
28 | from uliweb.utils.common import import_attr
29 |
30 | for k, v in settings.get_var('FORM_FIELDS_MAP', {}).items():
31 | form.fields_mapping[k] = import_attr(v)
32 |
33 |
--------------------------------------------------------------------------------
/uliweb/contrib/form/conf.py:
--------------------------------------------------------------------------------
1 | from uliweb.form import *
2 |
3 | #class ManageForm(Form):
4 | # debug_log = BooleanField(label='Debug Log:', key='ORM/DEBUG_LOG')
5 | # auto_create = BooleanField(label='Auto Create Table:', key='ORM/AUTO_CREATE')
6 | # connection = StringField(label='Database Connection String:', required=True, key='ORM/CONNECTION')
7 |
--------------------------------------------------------------------------------
/uliweb/contrib/form/info.ini:
--------------------------------------------------------------------------------
1 | [info]
2 | catalog = ''
3 | title = ''
4 | description = ''
5 | icon = ''
6 | author = ''
7 | version = ''
8 | homepage = ''
9 |
--------------------------------------------------------------------------------
/uliweb/contrib/form/settings.ini:
--------------------------------------------------------------------------------
1 | [FUNCTIONS]
2 | get_form = 'uliweb.contrib.form.get_form'
3 | make_form = 'uliweb.form.make_form'
4 |
5 | [VALIDATORS]
6 | #IS_IN_SET = 'uliweb.form.validators.IS_IN_SET'
7 | #IS_IMAGE = 'uliweb.form.validators.IS_IMAGE'
8 | #IS_PAST_DATE = 'uliweb.form.validators.IS_PAST_DATE'
9 | #IS_LENGTH_LESSTHAN = 'uliweb.form.validators.IS_LENGTH_LESSTHAN'
10 | #IS_LENGTH_GREATTHAN = 'uliweb.form.validators.IS_LENGTH_GREATTHAN'
11 | #IS_LENGTH_BETWEEN = 'uliweb.form.validators.IS_LENGTH_BETWEEN'
12 | #IS_URL = 'uliweb.form.validators.IS_URL'
13 |
14 | [GLOBAL_OBJECTS]
15 | validators = 'uliweb.contrib.form.validators'
16 |
17 | [BINDS]
18 | form.startup_installed = 'startup_installed', '#{appname}.startup_installed'
19 |
20 |
--------------------------------------------------------------------------------
/uliweb/contrib/generic/conf.py:
--------------------------------------------------------------------------------
1 | from uliweb.form import *
2 |
3 | #class ManageForm(Form):
4 | # debug_log = BooleanField(label='Debug Log:', key='ORM/DEBUG_LOG')
5 | # auto_create = BooleanField(label='Auto Create Table:', key='ORM/AUTO_CREATE')
6 | # connection = StringField(label='Database Connection String:', required=True, key='ORM/CONNECTION')
7 |
--------------------------------------------------------------------------------
/uliweb/contrib/generic/config.ini:
--------------------------------------------------------------------------------
1 | [DEPENDS]
2 | REQUIRED_APPS = [
3 | 'uliweb.contrib.orm',
4 | 'uliweb.contrib.form',
5 | ]
6 |
--------------------------------------------------------------------------------
/uliweb/contrib/generic/forms.py:
--------------------------------------------------------------------------------
1 | #coding=utf-8
2 | import uliweb.form as form
3 | from uliweb.form import *
4 | from uliweb.form.layout import QueryLayout
5 | from uliweb.i18n import gettext_lazy as _
6 |
7 | class NewStyleQueryLayout(QueryLayout):
8 | def get_more_button(self):
9 | return ''
10 |
11 | def post_layout(self):
12 | return '' % (_('more'), _('more'))
13 |
14 | class QueryForm(form.Form):
15 | form_buttons = form.Button(value=_('Search'), _class="btn btn-primary", type='submit')
16 | layout_class = NewStyleQueryLayout
17 | form_method = 'GET'
18 |
19 | def pre_html(self):
20 | return '''
21 |
22 |
23 | '''
24 |
25 | def post_html(self):
26 | buf = """
27 |
36 | """
37 | return buf
38 |
--------------------------------------------------------------------------------
/uliweb/contrib/generic/info.ini:
--------------------------------------------------------------------------------
1 | [info]
2 | catalog = ''
3 | title = ''
4 | description = ''
5 | icon = ''
6 | author = ''
7 | version = ''
8 | homepage = ''
9 |
--------------------------------------------------------------------------------
/uliweb/contrib/generic/settings.ini:
--------------------------------------------------------------------------------
1 | [FUNCTIONS]
2 | ListView = 'uliweb.utils.generic.ListView'
3 | SimpleListView = 'uliweb.utils.generic.SimpleListView'
4 | SelectListView = 'uliweb.utils.generic.SelectListView'
5 | AddView = 'uliweb.utils.generic.AddView'
6 | EditView = 'uliweb.utils.generic.EditView'
7 | DeleteView = 'uliweb.utils.generic.DeleteView'
8 | DetailView = 'uliweb.utils.generic.DetailView'
9 | QueryView = 'uliweb.utils.generic.QueryView'
10 | MultiView = '#{appname}.MultiView'
11 | get_model_columns = 'uliweb.utils.generic.get_model_columns'
12 |
13 | [FORMS]
14 | QueryForm = '#{appname}.forms.QueryForm'
15 |
16 | [MODEL_FIELD_TYPE_FORM_FILED_TYPE_MAP]
17 | TEXT = 'text'
18 | BIGINT = 'int'
19 | INTEGER = 'int'
20 | FLOAT = 'float'
21 | BOOLEAN = 'bool'
22 | DATETIME = 'datetime'
23 | DATE = 'date'
24 | DECIMAL = 'float'
25 | FILE = 'file'
26 | UUID = 'str'
27 |
28 | [FORM_FIELDS_MAP]
29 | reference_select = 'uliweb.utils.generic.ReferenceSelectField'
30 | manytomany_select = 'uliweb.utils.generic.ManyToManySelectField'
31 | remote_select = 'uliweb.utils.generic.RemoteField'
32 |
33 |
34 |
--------------------------------------------------------------------------------
/uliweb/contrib/generic/template_files/angularjs/config.ini:
--------------------------------------------------------------------------------
1 | [DEPENDS]
2 | REQUIRED_APPS = [
3 | 'uliweb.contrib.orm',
4 | 'uliweb.contrib.form',
5 | 'uliweb.contrib.i18n',
6 | 'plugs.ui.angularjs',
7 | 'plugs.ui.bootstrap',
8 | 'plugs.ui.bootheme',
9 | 'plugs.ui.jquery.jquery',
10 | 'plugs.ui.jquery.jqutils',
11 | 'plugs.ui.jquery.poshytip',
12 | 'plugs.ui.jquery.pnotify',
13 | ]
14 |
--------------------------------------------------------------------------------
/uliweb/contrib/generic/template_files/avalon/config.ini:
--------------------------------------------------------------------------------
1 | [DEPENDS]
2 | REQUIRED_APPS = [
3 | 'uliweb.contrib.orm',
4 | 'uliweb.contrib.form',
5 | 'uliweb.contrib.i18n',
6 | 'plugs.ui.avalon',
7 | 'plugs.ui.bootstrap',
8 | 'plugs.ui.bootheme',
9 | 'plugs.ui.jquery.jquery',
10 | 'plugs.ui.jquery.jqutils',
11 | 'plugs.ui.jquery.poshytip',
12 | 'plugs.ui.jquery.pnotify',
13 | ]
14 |
--------------------------------------------------------------------------------
/uliweb/contrib/generic/template_files/common/add.html:
--------------------------------------------------------------------------------
1 | #uliweb-template-tag:[[,]]
2 | {{extend "[[=layout]]"}}
3 |
4 | {{block content_main}}
5 | [[if addview_ajax:]]
6 | {{use "jqutils",ajaxForm=True}}
7 | [[pass]]
8 |
9 | {{=defined('title') or _('Add')}}
10 |
11 |
19 |
20 |
21 | [[if addview_ajax:]]
22 |
42 | [[pass]]
43 | {{end}}
--------------------------------------------------------------------------------
/uliweb/contrib/generic/template_files/common/ajax_add.html:
--------------------------------------------------------------------------------
1 | #uliweb-template-tag:[[,]]
2 |
3 | {{=defined('title') or _('Add')}}
4 |
5 |
10 |
11 |
--------------------------------------------------------------------------------
/uliweb/contrib/generic/template_files/common/ajax_edit.html:
--------------------------------------------------------------------------------
1 | #uliweb-template-tag:[[,]]
2 |
3 | {{=defined('title') or _('Edit')}}
4 |
5 |
10 |
11 |
--------------------------------------------------------------------------------
/uliweb/contrib/generic/template_files/common/edit.html:
--------------------------------------------------------------------------------
1 | #uliweb-template-tag:[[,]]
2 | {{extend "[[=layout]]"}}
3 |
4 | {{block content_main}}
5 | [[if addview_ajax:]]
6 | {{use "jqutils",ajaxForm=True}}
7 | [[pass]]
8 |
9 | {{=defined('title') or _('Edit')}}
10 |
11 |
19 |
20 |
21 | [[if addview_ajax:]]
22 |
42 | [[pass]]
43 | {{end}}
--------------------------------------------------------------------------------
/uliweb/contrib/generic/template_files/common/layout.html:
--------------------------------------------------------------------------------
1 | #uliweb-template-tag:[[,]]
2 |
3 | {{extend "layout.html"}}
4 |
5 | {{block menu}}
6 | {{menu('[[=appname]]')}}
7 | {{end}}
8 |
9 | {{block content}}
10 | {{include "bootstrap/inc_full.html"}}
11 | {{end}}
12 |
--------------------------------------------------------------------------------
/uliweb/contrib/generic/template_files/common/view.html:
--------------------------------------------------------------------------------
1 | #uliweb-template-tag:[[,]]
2 | {{extend "[[=layout]]"}}
3 |
4 | {{block content_main}}
5 |
6 |
7 |
{{=defined('title') or _('View')}}
8 |
9 | {{<< view.body}}
10 |
11 |
12 |
16 |
17 | {{end}}
18 |
--------------------------------------------------------------------------------
/uliweb/contrib/generic/template_files/easyui/config.ini:
--------------------------------------------------------------------------------
1 | [DEPENDS]
2 | REQUIRED_APPS = [
3 | 'uliweb.contrib.orm',
4 | 'uliweb.contrib.form',
5 | 'uliweb.contrib.i18n',
6 | 'plugs.ui.bootstrap',
7 | 'plugs.ui.bootheme',
8 | 'plugs.ui.jquery.jquery',
9 | 'plugs.ui.jquery.jqutils',
10 | 'plugs.ui.jquery.poshytip',
11 | 'plugs.ui.jquery.pnotify',
12 | 'plugs.ui.jquery.jqeasyui',
13 | ]
14 |
--------------------------------------------------------------------------------
/uliweb/contrib/generic/template_files/html/config.ini:
--------------------------------------------------------------------------------
1 | [DEPENDS]
2 | REQUIRED_APPS = [
3 | 'uliweb.contrib.orm',
4 | 'uliweb.contrib.form',
5 | 'uliweb.contrib.i18n',
6 | 'plugs.ui.bootstrap',
7 | 'plugs.ui.bootheme',
8 | 'plugs.ui.jquery.jquery',
9 | 'plugs.ui.jquery.jqutils',
10 | 'plugs.ui.jquery.poshytip',
11 | 'plugs.ui.jquery.pnotify',
12 | ]
13 |
--------------------------------------------------------------------------------
/uliweb/contrib/generic/template_files/mmgrid/config.ini:
--------------------------------------------------------------------------------
1 | [DEPENDS]
2 | REQUIRED_APPS = [
3 | 'uliweb.contrib.orm',
4 | 'uliweb.contrib.form',
5 | 'uliweb.contrib.i18n',
6 | 'plugs.ui.bootstrap',
7 | 'plugs.ui.bootheme',
8 | 'plugs.ui.jquery.jquery',
9 | 'plugs.ui.jquery.jqutils',
10 | 'plugs.ui.jquery.poshytip',
11 | 'plugs.ui.jquery.pnotify',
12 | 'plugs.ui.jquery.uligantt',
13 | ]
14 |
--------------------------------------------------------------------------------
/uliweb/contrib/i18n/__init__.py:
--------------------------------------------------------------------------------
1 | from uliweb.i18n import format_locale
2 | from uliweb.i18n import ugettext_lazy as _
3 |
4 | _LANGUAGES = {
5 | 'en_US':_('English'),
6 | 'zh_CN':_('Simplified Chinese'),
7 | }
8 | LANGUAGES = {}
9 | for k, v in _LANGUAGES.items():
10 | LANGUAGES[format_locale(k)] = v
11 |
12 | def startup_installed(sender):
13 | """
14 | @LANGUAGE_CODE
15 | """
16 | import os
17 | from uliweb.core.SimpleFrame import get_app_dir
18 | from uliweb.i18n import install, set_default_language
19 | from uliweb.utils.common import pkg, expand_path
20 |
21 | path = pkg.resource_filename('uliweb', '')
22 | _dirs = []
23 | for d in sender.settings.get_var('I18N/LOCALE_DIRS', []):
24 | _dirs.append(expand_path(d))
25 | localedir = ([os.path.normpath(sender.apps_dir + '/..')] +
26 | [get_app_dir(appname) for appname in sender.apps] + [path] + _dirs)
27 | install('uliweb', localedir)
28 | set_default_language(sender.settings.I18N.LANGUAGE_CODE)
29 |
30 | def prepare_default_env(sender, env):
31 | from uliweb.i18n import ugettext_lazy
32 | env['_'] = ugettext_lazy
33 |
--------------------------------------------------------------------------------
/uliweb/contrib/i18n/conf.py:
--------------------------------------------------------------------------------
1 | from uliweb.form import *
2 |
3 | class ManageForm(Form):
4 | language_code = StringField(label='Site Language Code:', key='I18N/LANGUAGE_CODE')
5 |
--------------------------------------------------------------------------------
/uliweb/contrib/i18n/info.ini:
--------------------------------------------------------------------------------
1 | [info]
2 | catalog = "System Apps"
3 | title = "I18n App"
4 | description = """Provide i18n function.
5 | """
--------------------------------------------------------------------------------
/uliweb/contrib/i18n/settings.ini:
--------------------------------------------------------------------------------
1 | [I18N]
2 | LANGUAGE_COOKIE_NAME = 'uliweb_language'
3 | LANGUAGE_CODE = 'en'
4 | LOCALE_DIRS = []
5 | SUPPORT_LANGUAGES = []
6 | URL_LANG_KEY = ''
7 |
8 | [MIDDLEWARES]
9 | i18n = 'uliweb.contrib.i18n.middle_i18n.I18nMiddle', 500
10 |
11 | [BINDS]
12 | i18n.startup_installed = 'startup_installed', 'uliweb.contrib.i18n.startup_installed'
13 | i18n.prepare_default_env = 'prepare_default_env', 'uliweb.contrib.i18n.prepare_default_env'
14 |
--------------------------------------------------------------------------------
/uliweb/contrib/jsonql/settings.ini:
--------------------------------------------------------------------------------
1 | [EXPOSES]
2 | jsonql = '/jsonql', 'uliweb.contrib.jsonql.views.jsonql'
3 |
4 | [JSONQL_SCHEMA]
5 |
6 | [BINDS]
7 | jsonql.after_init_apps = 'after_init_apps', 'uliweb.contrib.jsonql.after_init_apps'
8 |
9 | [JSONQL]
10 | query_limit = 10
11 |
12 |
--------------------------------------------------------------------------------
/uliweb/contrib/jsonql/views.py:
--------------------------------------------------------------------------------
1 | #coding=utf8
2 |
3 | import logging
4 |
5 | log = logging.getLogger(__name__)
6 |
7 | def jsonql():
8 | from . import query
9 | from uliweb import json
10 |
11 | print request.data
12 | d = request.json()
13 | try:
14 | result = query(d)
15 | result['status'] = '200'
16 | result['message'] = 'Success'
17 | except Exception as e:
18 | log.exception(e)
19 | result = {}
20 | result['status'] = '500'
21 | result['message'] = 'Error'
22 | return json(result)
23 |
--------------------------------------------------------------------------------
/uliweb/contrib/mail/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/limodou/uliweb/8bc827fa6bf7bf58aa8136b6c920fe2650c52422/uliweb/contrib/mail/__init__.py
--------------------------------------------------------------------------------
/uliweb/contrib/mail/conf.py:
--------------------------------------------------------------------------------
1 | from uliweb.form import *
2 |
3 | #class ManageForm(Form):
4 | # debug_log = BooleanField(label='Debug Log:', key='ORM/DEBUG_LOG')
5 | # auto_create = BooleanField(label='Auto Create Table:', key='ORM/AUTO_CREATE')
6 | # connection = StringField(label='Database Connection String:', required=True, key='ORM/CONNECTION')
7 |
--------------------------------------------------------------------------------
/uliweb/contrib/mail/info.ini:
--------------------------------------------------------------------------------
1 | [info]
2 | catalog = ''
3 | title = ''
4 | description = ''
5 | icon = ''
6 | author = ''
7 | version = ''
8 | homepage = ''
9 |
--------------------------------------------------------------------------------
/uliweb/contrib/mail/settings.ini:
--------------------------------------------------------------------------------
1 | [MAIL]
2 | HOST = 'localhost'
3 | PORT = 25
4 | USER = ''
5 | PASSWORD = ''
6 | BACKEND = 'uliweb.mail.backends.smtp'
7 | SENDMAIL_LOCATION = '/usr/sbin/sendmail'
8 |
--------------------------------------------------------------------------------
/uliweb/contrib/model_config/commands.py:
--------------------------------------------------------------------------------
1 | import os
2 | from uliweb import functions
3 | from optparse import make_option
4 | from uliweb.core.commands import Command, get_input, get_answer
5 |
6 | class MigrateModelConfigCommand(Command):
7 | name = 'migrate_model_config'
8 | help = 'Migrate model config models.'
9 | args = ''
10 | check_apps_dirs = True
11 | check_apps = False
12 | option_list = (
13 | make_option('-r', '--reset', dest='reset', action='store_true', help='Just reset model config models.'),
14 | )
15 |
16 | def reset_model(self, model_name, reset):
17 | M = functions.get_model(model_name, signal=False)
18 | engine = M.get_engine().engine
19 | if not M.table.exists(engine):
20 | print "Table %s(%s) is not existed. ... CREATED" % (model_name, M.tablename)
21 | M.table.create(engine)
22 | else:
23 | if reset:
24 | print "Table %s(%s) existed. ... RESET" % (model_name, M.tablename)
25 | M.table.drop(engine)
26 | M.table.create(engine)
27 | else:
28 | print "Table %s(%s) existed. ... MIGRATE" % (model_name, M.tablename)
29 | M.migrate()
30 |
31 | def handle(self, options, global_options, *args):
32 | self.get_application(global_options)
33 |
34 | self.reset_model('model_config', options.reset)
35 | self.reset_model('model_config_his', options.reset)
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/uliweb/contrib/model_config/conf.py:
--------------------------------------------------------------------------------
1 | from uliweb.form import *
2 |
3 | #class ManageForm(Form):
4 | # debug_log = BooleanField(label='Debug Log:', key='ORM/DEBUG_LOG')
5 | # auto_create = BooleanField(label='Auto Create Table:', key='ORM/AUTO_CREATE')
6 | # connection = StringField(label='Database Connection String:', required=True, key='ORM/CONNECTION')
7 |
--------------------------------------------------------------------------------
/uliweb/contrib/model_config/info.ini:
--------------------------------------------------------------------------------
1 | [info]
2 | catalog = ''
3 | title = ''
4 | description = ''
5 | icon = ''
6 | author = ''
7 | version = ''
8 | homepage = ''
9 |
--------------------------------------------------------------------------------
/uliweb/contrib/model_config/models.py:
--------------------------------------------------------------------------------
1 | from uliweb.orm import *
2 | from uliweb.utils.common import get_var
3 | from uliweb.i18n import ugettext_lazy as _
4 |
5 | class Model_Config(Model):
6 | model_name = Field(str, verbose_name=_('Model Name'), unique=True)
7 | display_name = Field(str, verbose_name=_('Display Name'))
8 | description = Field(str, verbose_name=_('Description'), max_length=255)
9 | uuid = Field(CHAR, verbose_name=_('UUID'), max_length=32)
10 | modified_user = Reference('user', verbose_name=_('Modified User'))
11 | modified_time = Field(datetime.datetime, verbose_name=_('Modified Time'),
12 | auto_now=True, auto_now_add=True)
13 | published_time = Field(datetime.datetime, verbose_name=_('Published Time'))
14 | version = Field(int)
15 |
16 | def __unicode__(self):
17 | return "%s(%s)" % (self.model_name, self.uuid)
18 |
19 | def get_instance(self):
20 | MCH = get_model('model_config_his', signal=False)
21 | return MCH.get((MCH.c.model_name==self.model_name) & (MCH.c.uuid==self.uuid))
22 |
23 | @classmethod
24 | def OnInit(cls):
25 | Index('model_cfg_idx', cls.c.model_name, cls.c.uuid)
26 |
27 | class Model_Config_His(Model):
28 | model_name = Field(str, verbose_name=_('Model Name'), index=True, required=True)
29 | display_name = Field(str, verbose_name=_('Display Name'))
30 | description = Field(str, verbose_name=_('Description'), max_length=255)
31 | table_name = Field(str, verbose_name=_('Tablename'))
32 | uuid = Field(CHAR, max_length=32)
33 | basemodel = Field(str, verbose_name=_('Base Model Class'),
34 | hint=_('Underlying model class path'))
35 | has_extension = Field(bool, verbose_name=_('Has Extension Model'))
36 | extension_model = Field(str, verbose_name=_('Extension Model Class'),
37 | hint=_('Underlying model class path'))
38 | fields = Field(TEXT)
39 | indexes = Field(TEXT)
40 | extension_fields = Field(TEXT)
41 | extension_indexes = Field(TEXT)
42 | version = Field(int)
43 | status = Field(CHAR, max_length=1, verbose_name=_('Publish Status'),
44 | choices=get_var('MODEL_SETTING/'), default='0')
45 | create_time = Field(datetime.datetime, verbose_name=_('Create Time'), auto_now_add=True)
46 | published_time = Field(datetime.datetime, verbose_name=_('Published Time'))
47 |
48 | @classmethod
49 | def OnInit(cls):
50 | Index('model_cfg_his_idx', cls.c.model_name, cls.c.uuid)
51 |
52 |
--------------------------------------------------------------------------------
/uliweb/contrib/model_config/settings.ini:
--------------------------------------------------------------------------------
1 | [MODEL_SETTING]
2 | STATUS = [('0', 'Unpublished'), ('1', 'Published')]
3 | COLUMN_TYPES = [
4 | (1, 'VARCHAR'), (2, 'CHAR'), (3, 'TEXT'), (4, 'BLOB'),
5 | (5, 'INTEGER'), (6, 'BIGINT'), (7, 'FLOAT'), (8, 'BOOLEAN'),
6 | (9, 'DATETIME'), (10, 'DATE'), (11, 'TIME'), (12, 'DECIMAL'),
7 | (13, 'FILE'), (14, 'PICKLE'), (15, 'UUID'), (16, 'JSON'),
8 | (17, 'BINARY'), (18, 'VARBINARY'),
9 | ]
10 | COLUMN_MAP = {1:'str', 2:'CHAR', 3:'TEXT', 4:'BLOB',
11 | 5:'int', 6:'BIGINT', 7:'float', 8:'bool',
12 | 9:'datetime.datetime', 10:'datetime.date', 11:'datetime.time',
13 | 12:'DECIMAL', 13:'FILE', 14:'PICKLE', 15:'UUID', 16:'JSON',
14 | 17:'BINARY', 18:'VARBINARY',
15 | }
16 |
17 | [MODELS]
18 | model_config = '#{appname}.models.Model_Config'
19 | model_config_his = '#{appname}.models.Model_Config_His'
20 |
21 | [BINDS]
22 | model_config.find_model = 'find_model', '#{appname}.find_model'
23 | model_config.load_models = 'load_models', '#{appname}.load_models'
24 | model_config.get_model = 'get_model', '#{appname}.get_model'
25 |
--------------------------------------------------------------------------------
/uliweb/contrib/objcache/conf.py:
--------------------------------------------------------------------------------
1 | from uliweb.form import *
2 |
3 | #class ManageForm(Form):
4 | # debug_log = BooleanField(label='Debug Log:', key='ORM/DEBUG_LOG')
5 | # auto_create = BooleanField(label='Auto Create Table:', key='ORM/AUTO_CREATE')
6 | # connection = StringField(label='Database Connection String:', required=True, key='ORM/CONNECTION')
7 |
--------------------------------------------------------------------------------
/uliweb/contrib/objcache/config.ini:
--------------------------------------------------------------------------------
1 | [DEPENDS]
2 | REQUIRED_APPS = [
3 | 'uliweb.contrib.redis_cli',
4 | 'uliweb.contrib.tables',
5 | ]
6 |
--------------------------------------------------------------------------------
/uliweb/contrib/objcache/info.ini:
--------------------------------------------------------------------------------
1 | [info]
2 | catalog = ''
3 | title = ''
4 | description = ''
5 | icon = ''
6 | author = ''
7 | version = ''
8 | homepage = ''
9 |
--------------------------------------------------------------------------------
/uliweb/contrib/objcache/settings.ini:
--------------------------------------------------------------------------------
1 | [BINDS]
2 | objcache.post_save = 'post_save', 'uliweb.contrib.objcache.post_save'
3 | objcache.post_delete = 'post_delete', 'uliweb.contrib.objcache.post_delete'
4 | objcache.get_object = 'get_object', 'uliweb.contrib.objcache.get_object'
5 | objcache.set_object = 'set_object', 'uliweb.contrib.objcache.set_object'
6 |
7 | [OBJCACHE]
8 | timeout = 24*3600
9 | #if set false then disable objcache functionality
10 | enable = True
11 | table_format = 'OC:%(engine)s:%(tableid)s:'
12 | key_format = table_format + '%(id)s'
13 |
14 | [OBJCACHE_TABLES]
15 | #tablename = {'fields':[default cache fileds], 'expire':xxx, 'key':callable(instance)|key_fieldname}
16 | #if no expire then default is 0, then no expire time at all
17 | #also the value can be list or tuple
18 | #user = {'fields':['username', 'nickname'], 'expire':24*3600}
--------------------------------------------------------------------------------
/uliweb/contrib/objcache/static/readme.txt:
--------------------------------------------------------------------------------
1 | This directory is used to store static files.
--------------------------------------------------------------------------------
/uliweb/contrib/objcache/templates/readme.txt:
--------------------------------------------------------------------------------
1 | This directory is used to store template files.
--------------------------------------------------------------------------------
/uliweb/contrib/orm/conf.py:
--------------------------------------------------------------------------------
1 | from uliweb.form import *
2 |
3 | class ManageForm(Form):
4 | debug_log = BooleanField(label='Debug Log:', key='ORM/DEBUG_LOG')
5 | auto_create = BooleanField(label='Auto Create Table:', key='ORM/AUTO_CREATE')
6 | connection = StringField(label='Database Connection String:', required=True, key='ORM/CONNECTION')
--------------------------------------------------------------------------------
/uliweb/contrib/orm/info.ini:
--------------------------------------------------------------------------------
1 | [info]
2 | catalog = "Database Apps"
3 | title = "Uliweb ORM App"
4 | description = """It bases on SQLAlchemy module, but works like GAE data store model.
5 | Support OneToOne, ManyToOne, ManyToMany relation.
6 | """
--------------------------------------------------------------------------------
/uliweb/contrib/orm/middle_notfound.py:
--------------------------------------------------------------------------------
1 | from uliweb import Middleware, error
2 | from uliweb.orm import NotFound
3 |
4 | class ORMNotfoundMiddle(Middleware):
5 | ORDER = 110
6 |
7 | def __init__(self, application, settings):
8 | pass
9 |
10 | def process_exception(self, request, exception):
11 | if isinstance(exception, NotFound):
12 | error("%s(%s) can't be found" % (exception.model.__name__, exception.id))
13 |
--------------------------------------------------------------------------------
/uliweb/contrib/orm/middle_orm_reset.py:
--------------------------------------------------------------------------------
1 | from uliweb import Middleware
2 | from uliweb.orm import set_dispatch_send, set_echo
3 |
4 | class ORMResetMiddle(Middleware):
5 | ORDER = 70
6 |
7 | def process_request(self, request):
8 | set_echo(False)
9 | set_dispatch_send(True)
--------------------------------------------------------------------------------
/uliweb/contrib/orm/middle_sqlmonitor.py:
--------------------------------------------------------------------------------
1 | from uliweb import Middleware
2 | from uliweb.orm import begin_sql_monitor, close_sql_monitor
3 |
4 | class SQLMonitorMiddle(Middleware):
5 | ORDER = 90
6 |
7 | def process_request(self, request):
8 | from uliweb import settings
9 |
10 | if 'sqlmonitor' in request.GET or settings.ORM.SQL_MONITOR:
11 | self.monitor = begin_sql_monitor(settings.ORM.get('SQL_MONITOR_LENGTH', 70), record_details=False)
12 |
13 | def process_response(self, request, response):
14 | from uliweb import settings
15 |
16 | if 'sqlmonitor' in request.GET or settings.ORM.SQL_MONITOR:
17 | self.monitor.print_(request.path)
18 | close_sql_monitor(self.monitor)
19 | return response
20 |
21 | def process_exception(self, request, exception):
22 | from uliweb import settings
23 |
24 | if 'sqlmonitor' in request.GET or settings.ORM.SQL_MONITOR:
25 | self.monitor.print_(request.path)
26 | close_sql_monitor(self.monitor)
--------------------------------------------------------------------------------
/uliweb/contrib/orm/middle_transaction.py:
--------------------------------------------------------------------------------
1 | from uliweb import Middleware
2 | from uliweb.orm import Begin, CommitAll, RollbackAll, set_echo
3 |
4 | class TransactionMiddle(Middleware):
5 | ORDER = 80
6 |
7 | def __init__(self, application, settings):
8 | self.settings = settings
9 |
10 | def process_request(self, request):
11 | Begin()
12 |
13 | def process_response(self, request, response):
14 | from uliweb import response as res
15 | try:
16 | return response
17 | finally:
18 | CommitAll()
19 |
20 | #add post_commit process
21 | if hasattr(response, 'post_commit') and response.post_commit:
22 | response.post_commit()
23 |
24 | if response is not res and hasattr(res, 'post_commit') and res.post_commit:
25 | res.post_commit()
26 |
27 | def process_exception(self, request, exception):
28 | RollbackAll()
29 |
--------------------------------------------------------------------------------
/uliweb/contrib/orm/requirements.txt:
--------------------------------------------------------------------------------
1 | SQLAlchemy > 0.7
2 | MySQL-python
3 | uliweb-alembic
--------------------------------------------------------------------------------
/uliweb/contrib/orm/settings.ini:
--------------------------------------------------------------------------------
1 | [ORM]
2 | DEBUG_LOG = False
3 | AUTO_CREATE = False
4 | AUTO_TRANSACTION_IN_NOTWEB = False
5 | AUTO_TRANSACTION_IN_WEB = False
6 | CHECK_MAX_LENGTH = False
7 | CONNECTION = 'sqlite:///database.db'
8 | CONNECTION_ARGS = {}
9 | #long or short
10 | CONNECTION_TYPE = 'long'
11 | STRATEGY = 'threadlocal'
12 | PK_TYPE = 'int'
13 | CONNECTIONS = {}
14 | TABLENAME_CONVERTER = None
15 | NULLABLE = True
16 | SERVER_DEFAULT = False
17 | MANYTOMANY_INDEX_REVERSE = False
18 | #make none condition to '' or raise Exception
19 | #you can use 'empty' or 'exception', if '' it'll be skipped
20 | PATCH_NONE = 'empty'
21 | ENCRYPT_PASSWORD = False
22 |
23 | [BINDS]
24 | orm.after_init_apps = 'after_init_apps', 'uliweb.contrib.orm.after_init_apps'
25 |
26 | [MIDDLEWARES]
27 | transaction = 'uliweb.contrib.orm.middle_transaction.TransactionMiddle'
28 | orm_reset = 'uliweb.contrib.orm.middle_orm_reset.ORMResetMiddle'
29 |
30 | [FUNCTIONS]
31 | get_model = 'uliweb.orm.get_model'
32 | get_object = 'uliweb.orm.get_object'
33 | get_cached_object = 'uliweb.orm.get_cached_object'
34 | set_echo = 'uliweb.orm.set_echo'
35 |
36 | [GLOBAL_OBJECTS]
37 | models = 'uliweb.contrib.orm.models'
--------------------------------------------------------------------------------
/uliweb/contrib/orm/templates/alembic/README:
--------------------------------------------------------------------------------
1 | Generic single-database configuration.
--------------------------------------------------------------------------------
/uliweb/contrib/orm/templates/alembic/alembic.ini:
--------------------------------------------------------------------------------
1 | # A generic, single database configuration.
2 |
3 | [alembic]
4 | # path to migration scripts
5 | script_location = {{=script_location}}
6 |
7 | # template used to generate migration files
8 | # file_template = %%(rev)s_%%(slug)s
9 |
10 | sqlalchemy.url = {{=connection}}
11 | engine_name = {{=engine_name}}
12 |
13 |
14 | # Logging configuration
15 | [loggers]
16 | keys = root,sqlalchemy,alembic
17 |
18 | [handlers]
19 | keys = colored
20 |
21 | [formatters]
22 | keys = generic
23 |
24 | [logger_root]
25 | level = WARN
26 | handlers =
27 | qualname =
28 |
29 | [logger_sqlalchemy]
30 | level = WARN
31 | handlers =
32 | qualname = sqlalchemy.engine
33 |
34 | [logger_alembic]
35 | level = INFO
36 | handlers = colored
37 | qualname = alembic
38 |
39 | [handler_colored]
40 | class = alembic.coloredlog.ColoredStreamHandler
41 | args = (sys.stderr,)
42 | level = NOTSET
43 | formatter = generic
44 |
45 | [formatter_generic]
46 | format = %(levelname)-5.5s [%(name)s] %(message)s
47 | datefmt = %H:%M:%S
48 |
--------------------------------------------------------------------------------
/uliweb/contrib/orm/templates/alembic/script.py.mako:
--------------------------------------------------------------------------------
1 | """${message}
2 |
3 | Revision ID: ${up_revision}
4 | Revises: ${down_revision}
5 | Create Date: ${create_date}
6 |
7 | """
8 |
9 | # revision identifiers, used by Alembic.
10 | revision = ${repr(up_revision)}
11 | down_revision = ${repr(down_revision)}
12 |
13 | from alembic import op
14 | import sqlalchemy as sa
15 | ${imports if imports else ""}
16 |
17 | def upgrade():
18 | ${upgrades if upgrades else "pass"}
19 |
20 |
21 | def downgrade():
22 | ${downgrades if downgrades else "pass"}
23 |
--------------------------------------------------------------------------------
/uliweb/contrib/orm/templates/alembic/versions/readme.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/limodou/uliweb/8bc827fa6bf7bf58aa8136b6c920fe2650c52422/uliweb/contrib/orm/templates/alembic/versions/readme.txt
--------------------------------------------------------------------------------
/uliweb/contrib/rbac/__init__.py:
--------------------------------------------------------------------------------
1 | from rbac import *
2 |
3 | def prepare_default_env(sender, env):
4 | from uliweb import functions
5 |
6 | env['has_permission'] = functions.has_permission
7 | env['has_role'] = functions.has_role
8 |
9 | def after_init_apps(sender):
10 | from uliweb import settings
11 | from rbac import register_role_method
12 |
13 | if 'ROLES' in settings:
14 | for k, v in settings.get_var('ROLES', {}).iteritems():
15 | if isinstance(v, (list, tuple)) and len(v) > 1:
16 | method = v[1]
17 | if method:
18 | register_role_method(k, method)
19 |
20 | def startup_installed(sender):
21 | from uliweb.core import template
22 | from .tags import PermissionNode, RoleNode
23 |
24 | template.register_node('permission', PermissionNode)
25 | template.register_node('role', RoleNode)
26 |
--------------------------------------------------------------------------------
/uliweb/contrib/rbac/conf.py:
--------------------------------------------------------------------------------
1 | from uliweb.form import *
2 |
3 | #class ManageForm(Form):
4 | # debug_log = BooleanField(label='Debug Log:', key='ORM/DEBUG_LOG')
5 | # auto_create = BooleanField(label='Auto Create Table:', key='ORM/AUTO_CREATE')
6 | # connection = StringField(label='Database Connection String:', required=True, key='ORM/CONNECTION')
7 |
--------------------------------------------------------------------------------
/uliweb/contrib/rbac/info.ini:
--------------------------------------------------------------------------------
1 | [info]
2 | catalog = ''
3 | title = ''
4 | description = ''
5 | icon = ''
6 | author = ''
7 | version = ''
8 | homepage = ''
9 |
--------------------------------------------------------------------------------
/uliweb/contrib/rbac/models.py:
--------------------------------------------------------------------------------
1 | from uliweb.orm import *
2 |
3 | class RoleCategory(Model):
4 | name = Field(str, max_length=30)
5 | parent = SelfReference(collection_name='children', nullable=True, default=0)
6 | number_of_roles = Field(int)
7 |
8 | def __unicode__(self):
9 | return self.name
10 |
11 | @classmethod
12 | def OnInit(cls):
13 | Index('rolecategory_idx', cls.c.parent, cls.c.name, unique=True)
14 |
15 | class Permission(Model):
16 | name = Field(str, max_length=80, required=True)
17 | description = Field(str, max_length=255)
18 | props = Field(PICKLE)
19 |
20 | def get_users(self):
21 | for role in self.perm_roles.all():
22 | for u in role.users.all():
23 | yield u
24 |
25 | def get_users_ids(self):
26 | for role in self.perm_roles.all():
27 | for u in role.users.ids():
28 | yield u
29 |
30 | def __unicode__(self):
31 | return self.name
32 |
33 | class Role(Model):
34 | name = Field(str, max_length=80, required=True)
35 | description = Field(str, max_length=255)
36 | category = Reference('rolecategory', nullable=True)
37 | reserve = Field(bool)
38 | users = ManyToMany('user', collection_name='user_roles')
39 | permissions = ManyToMany('permission', through='role_perm_rel', collection_name='perm_roles')
40 | usergroups = ManyToMany('usergroup', collection_name='usergroup_roles')
41 | relative_usergroup = Reference('usergroup', nullable=True)
42 |
43 | def __unicode__(self):
44 | return self.name
45 |
46 | def usergroups_has_user(self,user):
47 | for usergroup in list(self.usergroups.all()):
48 | if usergroup.users.has(user):
49 | return usergroup
50 | return False
51 |
52 | class Role_Perm_Rel(Model):
53 | role = Reference('role')
54 | permission = Reference('permission')
55 | props = Field(PICKLE)
56 |
57 |
--------------------------------------------------------------------------------
/uliweb/contrib/rbac/settings.ini:
--------------------------------------------------------------------------------
1 | [MODELS]
2 | role = 'uliweb.contrib.rbac.models.Role'
3 | permission = 'uliweb.contrib.rbac.models.Permission'
4 | role_perm_rel = 'uliweb.contrib.rbac.models.Role_Perm_Rel'
5 | rolecategory = 'uliweb.contrib.rbac.models.RoleCategory'
6 |
7 | [ROLES]
8 | superuser = _('Super User'), 'uliweb.contrib.rbac.superuser', True
9 | anonymous = _('Anonymous User'), 'uliweb.contrib.rbac.anonymous', True
10 | trusted = _('Trusted User'), 'uliweb.contrib.rbac.trusted', True
11 |
12 | #[ROLES_PERMISSIONS]
13 | #This section defines relationship between roles and permissions
14 | #the format should be
15 | #permission_name = role
16 | #permission_name = role1, role2, ...
17 | #permission_name = (role1, role_prop1),(role2, role_prop2)
18 |
19 | [FUNCTIONS]
20 | has_role = 'uliweb.contrib.rbac.has_role'
21 | has_permission = 'uliweb.contrib.rbac.has_permission'
22 |
23 | [DECORATORS]
24 | check_role = 'uliweb.contrib.rbac.check_role'
25 | check_permission = 'uliweb.contrib.rbac.check_permission'
26 |
27 | [BINDS]
28 | rbac.prepare_default_env = 'prepare_default_env', 'uliweb.contrib.rbac.prepare_default_env'
29 | rbac.after_init_apps = 'after_init_apps', 'uliweb.contrib.rbac.after_init_apps'
30 | rbac.startup_installed = 'startup_installed', 'uliweb.contrib.rbac.startup_installed'
31 |
--------------------------------------------------------------------------------
/uliweb/contrib/rbac/tags.py:
--------------------------------------------------------------------------------
1 | from uliweb.core.template import BaseBlockNode
2 |
3 | class PermissionNode(BaseBlockNode):
4 | def generate(self, writer):
5 | writer.write_line('if functions.has_permission(request.user, %s):' %
6 | self.statement, self.line)
7 | with writer.indent():
8 | self.body.generate(writer)
9 | writer.write_line("pass", self.line)
10 |
11 | class RoleNode(BaseBlockNode):
12 | def generate(self, writer):
13 | writer.write_line('if functions.has_role(request.user, %s):' %
14 | self.statement, self.line)
15 | with writer.indent():
16 | self.body.generate(writer)
17 | writer.write_line("pass", self.line)
18 |
--------------------------------------------------------------------------------
/uliweb/contrib/recorder/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/limodou/uliweb/8bc827fa6bf7bf58aa8136b6c920fe2650c52422/uliweb/contrib/recorder/__init__.py
--------------------------------------------------------------------------------
/uliweb/contrib/recorder/commands.py:
--------------------------------------------------------------------------------
1 | import os, sys
2 | from uliweb.core.commands import Command, get_answer, CommandManager, get_commands
3 | from optparse import make_option
4 | import inspect
5 |
6 | class RecorderCommand(CommandManager):
7 | name = 'recorder'
8 | args = 'recorder_commands'
9 | check_apps_dirs = True
10 |
11 | def get_commands(self, global_options):
12 | import subcommands
13 | cmds = get_commands(subcommands)
14 | return cmds
15 |
16 |
--------------------------------------------------------------------------------
/uliweb/contrib/recorder/conf.py:
--------------------------------------------------------------------------------
1 | from uliweb.form import *
2 |
3 | #class ManageForm(Form):
4 | # debug_log = BooleanField(label='Debug Log:', key='ORM/DEBUG_LOG')
5 | # auto_create = BooleanField(label='Auto Create Table:', key='ORM/AUTO_CREATE')
6 | # connection = StringField(label='Database Connection String:', required=True, key='ORM/CONNECTION')
7 |
--------------------------------------------------------------------------------
/uliweb/contrib/recorder/info.ini:
--------------------------------------------------------------------------------
1 | [info]
2 | catalog = ''
3 | title = ''
4 | description = ''
5 | icon = ''
6 | author = ''
7 | version = ''
8 | homepage = ''
9 |
--------------------------------------------------------------------------------
/uliweb/contrib/recorder/models.py:
--------------------------------------------------------------------------------
1 | from uliweb.orm import *
2 |
3 |
4 | class UliwebRecorderStatus(Model):
5 | status = Field(CHAR, max_length=1, choices=[('S', 'start'), ('E', 'stop')], default='E')
6 |
7 |
8 | class UliwebRecorder(Model):
9 | """
10 | Used to store the request info, and will be replay later to test.
11 | """
12 | method = Field(str, max_length=10)
13 | url = Field(TEXT)
14 | post_data = Field(TEXT)
15 | post_data_is_text = Field(bool)
16 | status_code = Field(int)
17 | response_data = Field(TEXT)
18 | response_data_is_text = Field(bool)
19 | user = Reference('user')
20 | begin_datetime = Field(datetime.datetime, auto_now_add=True, index=True)
21 | end_datetime = Field(datetime.datetime, auto_now=True)
22 | time_used = Field(float)
23 |
--------------------------------------------------------------------------------
/uliweb/contrib/recorder/settings.ini:
--------------------------------------------------------------------------------
1 | [MODELS]
2 | uliwebrecorder = 'uliweb.contrib.recorder.models.UliwebRecorder'
3 | uliwebrecorderstatus = 'uliweb.contrib.recorder.models.UliwebRecorderStatus'
4 |
5 | [MIDDLEWARES]
6 | uliwebrecorder = 'uliweb.contrib.recorder.middle_recorder.RecorderrMiddle'
7 |
8 | [ULIWEBRECORDER]
9 | response_text = False
10 | text_content_types = [
11 | 'text/*',
12 | 'application/x-www-form-urlencoded',
13 | 'application/*xml',
14 | 'application/json',
15 | 'application/*javascript',
16 | ]
17 | max_content_length = 64*1024
18 | recorder_type = 'stream' # stream | mq | db
19 | mq_name: 'recorder_mq'
20 |
21 | [FUNCTIONS]
22 | get_redis = 'uliweb.contrib.redis_cli.get_redis'
23 |
--------------------------------------------------------------------------------
/uliweb/contrib/recorder/template_files/recorder.tpl:
--------------------------------------------------------------------------------
1 |
2 | def test(c, log, counter):
3 | {{for row in rows:}}{{<< row}}
4 | {{pass}}
5 |
6 | if __name__ == '__main__':
7 | import os
8 | from datetime import datetime
9 | from uliweb.utils.test import client, Counter
10 |
11 | c = client('.')
12 | print 'Current directory is %s' % os.getcwd()
13 | print
14 |
15 | #log = 'recorder_test_%s.log' % datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
16 | log = True
17 |
18 | counter = Counter()
19 | test(c, log, counter)
20 |
21 | print
22 | print 'Total cases is %d, %d passed, %d failed' % (counter.total,
23 | counter.passed, counter.failed)
--------------------------------------------------------------------------------
/uliweb/contrib/recorder/template_files/recorder_row.tpl:
--------------------------------------------------------------------------------
1 | c.test_url('{{<= 2.6', or '= 2.6', only main version number will be tested,
7 | #so 2.6.12 should be treated as 2.6
8 | #empty will not check version
9 | check_version = ''
10 |
11 | [FUNCTIONS]
12 | get_redis = 'uliweb.contrib.redis_cli.get_redis'
13 | get_lock = 'uliweb.contrib.redis_cli.get_lock'
14 | set_lock = 'uliweb.contrib.redis_cli.set_lock'
15 | mbrpoplpush = 'uliweb.contrib.redis_cli.mbrpoplpush'
16 | redis_clear_prefix = 'uliweb.contrib.redis_cli.clear_prefix'
17 | redis_count_prefix = 'uliweb.contrib.redis_cli.count_prefix'
18 |
19 | [BINDS]
20 | #redis_cli.after_init_apps = 'after_init_apps', 'uliweb.contrib.redis_cli.after_init_apps'
21 |
--------------------------------------------------------------------------------
/uliweb/contrib/secretkey/__init__.py:
--------------------------------------------------------------------------------
1 | from uliweb import settings, functions
2 | from uliweb.utils.common import import_attr, application_path
3 | from hashlib import md5
4 |
5 | def get_cipher(key=None, keyfile=None):
6 | """
7 | Get cipher object, and then you can invoke:
8 | des = get_cipher()
9 | d = des.encrpy('Hello')
10 | print des.descrpy(d)
11 | """
12 | des_func = import_attr(settings.SECRETKEY.CIPHER_CLS)
13 | kwargs = settings.SECRETKEY.CIPHER_ARGS
14 |
15 | if not key:
16 | key = functions.get_cipher_key(keyfile)
17 | cipher = des_func(key, **kwargs)
18 | return cipher
19 |
20 | def encrypt(v, key=None, keyfile=None):
21 | """
22 | Encrypt an string
23 | """
24 | cipher = functions.get_cipher(key, keyfile)
25 | return cipher.encrypt(v)
26 |
27 | def decrypt(v, key=None, keyfile=None):
28 | """
29 | Encrypt an string
30 | """
31 | cipher = functions.get_cipher(key, keyfile)
32 | return cipher.decrypt(v)
33 |
34 | def get_key(keyfile=None):
35 | """
36 | Read the key content from secret_file
37 | """
38 | keyfile = keyfile or application_path(settings.SECRETKEY.SECRET_FILE)
39 | with file(keyfile, 'rb') as f:
40 | return f.read()
41 |
42 | def get_cipher_key(keyfile=None):
43 | """
44 | Create key which will be used in des, because des need 8bytes chars
45 | """
46 | _key = get_key(keyfile)
47 | _k = md5(_key).hexdigest()
48 | key = xor(_k[:8], _k[8:16], _k[16:24], _k[24:])
49 | return key
50 |
51 | def xor(*args):
52 | arg1 = args[0]
53 | for arg in args[1:]:
54 | s = []
55 | for i, ch in enumerate(arg):
56 | s.append(chr(ord(arg1[i]) ^ ord(ch)))
57 | arg1 = ''.join(s)
58 | return arg1
59 |
--------------------------------------------------------------------------------
/uliweb/contrib/secretkey/commands.py:
--------------------------------------------------------------------------------
1 | import os
2 | from uliweb.core.commands import Command
3 | from optparse import make_option
4 |
5 | class MakeKeyCommand(Command):
6 | name = 'makekey'
7 | help = 'Make secret key to to a file.'
8 | option_list = (
9 | make_option('-o', dest="output",
10 | help='Output key file name.'),
11 | )
12 |
13 | def handle(self, options, global_options, *args):
14 | from random import choice
15 | from uliweb.core.SimpleFrame import get_settings
16 | from uliweb.core.commands import get_answer
17 |
18 | settings = get_settings(global_options.project, settings_file=global_options.settings,
19 | local_settings_file=global_options.local_settings)
20 | output = options.output or settings.SECRETKEY.SECRET_FILE
21 | keyfile = os.path.join(global_options.project, output)
22 | if os.path.exists(keyfile):
23 | message = 'The file %s is already existed, do you want to overwrite' % keyfile
24 | ans = 'Y' if global_options.yes else get_answer(message)
25 | if ans != 'Y':
26 | return
27 | print 'Creating secretkey file %s...' % keyfile,
28 | f = open(keyfile, 'wb')
29 | secret_key = ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(settings.SECRETKEY.KEY_LENGTH)])
30 | f.write(secret_key)
31 | print 'OK'
32 |
33 |
34 | class EncryptCommand(Command):
35 | name = 'encrypt'
36 | args = 'string'
37 | help = 'Encrypt a string.'
38 | option_list = (
39 | make_option('-b', '--base64', dest="base64", action='store_true',
40 | help='Encode to base64 encoding.'),
41 | make_option('-h', '--hex', dest="hex", action='store_true',
42 | help='Encode to hex encoding.'),
43 | )
44 |
45 | def handle(self, options, global_options, *args):
46 | from uliweb import functions
47 |
48 | self.get_application(global_options)
49 |
50 | v = functions.encrypt(args[0])
51 | if options.base64:
52 | import base64
53 | v = base64.encodestring(v)
54 | if options.hex:
55 | v = v.encode('hex')
56 | print v
57 |
58 | class DecryptCommand(Command):
59 | name = 'decrypt'
60 | args = 'string'
61 | help = 'Decrypt a string.'
62 | option_list = (
63 | make_option('-b', '--base64', dest="base64", action='store_true',
64 | help='Decode from base64 encoding.'),
65 | make_option('-h', '--hex', dest="hex", action='store_true',
66 | help='Decode from hex encoding.'),
67 | )
68 |
69 | def handle(self, options, global_options, *args):
70 | from uliweb import functions
71 |
72 | self.get_application(global_options)
73 |
74 | if options.base64:
75 | import base64
76 | v = base64.decodestring(args[0])
77 | elif options.hex:
78 | v = args[0].decode('hex')
79 | else:
80 | v = args[0]
81 | v = functions.decrypt(v)
82 | print v
83 |
--------------------------------------------------------------------------------
/uliweb/contrib/secretkey/conf.py:
--------------------------------------------------------------------------------
1 | from uliweb.form import *
2 |
3 | #class ManageForm(Form):
4 | # debug_log = BooleanField(label='Debug Log:', key='ORM/DEBUG_LOG')
5 | # auto_create = BooleanField(label='Auto Create Table:', key='ORM/AUTO_CREATE')
6 | # connection = StringField(label='Database Connection String:', required=True, key='ORM/CONNECTION')
7 |
--------------------------------------------------------------------------------
/uliweb/contrib/secretkey/info.ini:
--------------------------------------------------------------------------------
1 | [info]
2 | catalog = ''
3 | title = ''
4 | description = 'Using it you need to install pyDes or config cipher class in settings'
5 | icon = ''
6 | author = ''
7 | version = ''
8 | homepage = ''
9 |
--------------------------------------------------------------------------------
/uliweb/contrib/secretkey/settings.ini:
--------------------------------------------------------------------------------
1 | [SECRETKEY]
2 | SECRET_FILE = 'secret.key'
3 | KEY_LENGTH = 50
4 | CIPHER_CLS = 'pyDes.des'
5 | CIPHER_ARGS = {'mode':1, 'IV':"\0\0\0\0\0\0\0\0", 'pad':None, 'padmode':2}
6 |
7 | [FUNCTIONS]
8 | get_cipher = 'uliweb.contrib.secretkey.get_cipher'
9 | get_key = 'uliweb.contrib.secretkey.get_key'
10 | get_cipher_key = 'uliweb.contrib.secretkey.get_cipher_key'
11 | encrypt = 'uliweb.contrib.secretkey.encrypt'
12 | decrypt = 'uliweb.contrib.secretkey.decrypt'
--------------------------------------------------------------------------------
/uliweb/contrib/sequence/__init__.py:
--------------------------------------------------------------------------------
1 | from uliweb import functions
2 | from time import sleep
3 |
4 | def get_sequence(key, default=1, step=1, retry_times=None, retry_waittime=None):
5 | from uliweb.orm import SaveError
6 | from uliweb import settings
7 |
8 | assert step > 0 and default > 0
9 |
10 | Sequence = functions.get_model('sequence')
11 | i = 0
12 | waittime = retry_waittime or settings.get_var('SEQUENCE/retry_waittime', 0.05)
13 | retry_times = retry_times or settings.get_var('SEQUENCE/retry_times', 3)
14 | while 1:
15 | try:
16 | row = Sequence.get(Sequence.c.key==key)
17 | if row:
18 | row.value = row.value + step
19 | row.save(version=True)
20 | else:
21 | row = Sequence(key=key, value=(default+step-1))
22 | row.save()
23 | break
24 | except SaveError:
25 | i += 1
26 | if i == retry_times:
27 | raise
28 | else:
29 | sleep(waittime)
30 |
31 | return row.value
32 |
33 | def set_sequence(key, value):
34 | assert value > 0
35 |
36 | Sequence = functions.get_model('sequence')
37 | row = Sequence.get(Sequence.c.key==key)
38 | if row:
39 | row.value = value
40 | row.save(version=True)
41 | else:
42 | row = Sequence(key=key, value=value)
43 | row.save()
44 | return row
45 |
46 |
--------------------------------------------------------------------------------
/uliweb/contrib/sequence/conf.py:
--------------------------------------------------------------------------------
1 | from uliweb.form import *
2 |
3 | #class ManageForm(Form):
4 | # debug_log = BooleanField(label='Debug Log:', key='ORM/DEBUG_LOG')
5 | # auto_create = BooleanField(label='Auto Create Table:', key='ORM/AUTO_CREATE')
6 | # connection = StringField(label='Database Connection String:', required=True, key='ORM/CONNECTION')
7 |
--------------------------------------------------------------------------------
/uliweb/contrib/sequence/config.ini:
--------------------------------------------------------------------------------
1 | [DEPENDS]
2 | REQUIRED_APPS = [
3 | 'uliweb.contrib.orm',
4 | ]
--------------------------------------------------------------------------------
/uliweb/contrib/sequence/info.ini:
--------------------------------------------------------------------------------
1 | [info]
2 | catalog = ''
3 | title = ''
4 | description = ''
5 | icon = ''
6 | author = ''
7 | version = ''
8 | homepage = ''
9 |
--------------------------------------------------------------------------------
/uliweb/contrib/sequence/models.py:
--------------------------------------------------------------------------------
1 | #coding=utf8
2 |
3 | from uliweb.orm import *
4 |
5 | class Sequence(Model):
6 | key = Field(str, max_length=80, required=True, unique=True, index=True)
7 | value = Field(int)
8 | version = Field(int)
9 | modified_time = Field(datetime.datetime, auto_now=True, auto_now_add=True)
10 |
11 | def __unicode__(self):
12 | return self.key+'/'+str(self.value)
13 |
--------------------------------------------------------------------------------
/uliweb/contrib/sequence/settings.ini:
--------------------------------------------------------------------------------
1 | [MODELS]
2 | sequence = 'uliweb.contrib.sequence.models.Sequence'
3 |
4 | [FUNCTIONS]
5 | get_sequence = 'uliweb.contrib.sequence.get_sequence'
6 | set_sequence = 'uliweb.contrib.sequence.set_sequence'
7 |
8 | [SEQUENCE]
9 | retry_waittime = 0.05
10 | retry_times = 3
--------------------------------------------------------------------------------
/uliweb/contrib/session/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/limodou/uliweb/8bc827fa6bf7bf58aa8136b6c920fe2650c52422/uliweb/contrib/session/__init__.py
--------------------------------------------------------------------------------
/uliweb/contrib/session/conf.py:
--------------------------------------------------------------------------------
1 | from uliweb.form import *
2 |
3 | class ManageForm(Form):
4 | type = SelectField(label='Session Type:', default='file', choices=[('file', 'File Based'), ('dbm', 'DMB Based'), ('database', 'Database Based')], key='SESSION/type')
5 | url = StringField(label='Connection URL(For Database):', default='sqlite:///session.db', key='SESSION_STORAGE/url')
6 | table_name = StringField(label='Table name(For Database):', default='uliweb_session', key='SESSION_STORAGE/table_name')
7 | data_dir = StringField(label='Session Path(File,DBM):', default='./sessions', key='SESSION_STORAGE/data_dir')
8 | timeout = IntField(label='Timeout:', required=True, default=3600, key='SESSION/timeout')
9 | cookie_timeout = IntField(label='Cookie Expire Time:', default=None, key='SESSION_COOKIE/timeout')
10 | cookie_domain = StringField(label='Cookie Domain:', default=None, key='SESSION_COOKIE/domain')
11 | cookie_path = StringField(label='Cookie Path:', default='/', key='SESSION_COOKIE/path')
12 | cookie_path = BooleanField(label='Cookie Secure:', default=False, key='SESSION_COOKIE/secure')
13 |
--------------------------------------------------------------------------------
/uliweb/contrib/session/info.ini:
--------------------------------------------------------------------------------
1 | [info]
2 | catalog = "System Apps"
3 | title = "Session Manage App"
4 | description = """Session management.
5 | """
--------------------------------------------------------------------------------
/uliweb/contrib/session/settings.ini:
--------------------------------------------------------------------------------
1 | [SESSION]
2 | type = 'file'
3 | #if set session.remember, then use remember_me_timeout timeout(second)
4 | remember_me_timeout = 30*24*3600
5 | #if not set session.remember, then use timeout(second)
6 | timeout = 3600
7 | force = False
8 | serial_cls = None
9 |
10 | [SESSION_STORAGE]
11 | data_dir = './sessions'
12 |
13 | [SESSION_COOKIE]
14 | cookie_id = 'uliweb_session_id'
15 | #only enabled when user not set session.cookie.expiry_time and session.remember is False
16 | #so if the value is None, then is means browser session
17 | timeout = None
18 | domain = None
19 | path = '/'
20 | secure = None
21 |
22 | [MIDDLEWARES]
23 | session = 'uliweb.contrib.session.middle_session.SessionMiddle', 50
24 |
25 | [LOG.Loggers]
26 | uliweb.contrib.auth = {'level': 'info', 'propagate': 0}
27 |
--------------------------------------------------------------------------------
/uliweb/contrib/soap/conf.py:
--------------------------------------------------------------------------------
1 | from uliweb.form import *
2 |
3 | #class ManageForm(Form):
4 | # debug_log = BooleanField(label='Debug Log:', key='ORM/DEBUG_LOG')
5 | # auto_create = BooleanField(label='Auto Create Table:', key='ORM/AUTO_CREATE')
6 | # connection = StringField(label='Database Connection String:', required=True, key='ORM/CONNECTION')
7 |
--------------------------------------------------------------------------------
/uliweb/contrib/soap/info.ini:
--------------------------------------------------------------------------------
1 | [info]
2 | catalog = ''
3 | title = ''
4 | description = ''
5 | icon = ''
6 | author = ''
7 | version = ''
8 | homepage = ''
9 |
--------------------------------------------------------------------------------
/uliweb/contrib/soap/settings.ini:
--------------------------------------------------------------------------------
1 | [DECORATORS]
2 | soap = 'uliweb.contrib.soap.soap'
3 |
4 | [EXPOSES]
5 | soap_url = '/SOAP', 'uliweb.contrib.soap.views.SoapView.soap'
6 |
7 | [SOAP]
8 | namespace = None
9 | documentation = 'Uliweb Soap Service'
10 | name = 'UliwebSoap'
11 | prefix = 'pys'
--------------------------------------------------------------------------------
/uliweb/contrib/soap/static/readme.txt:
--------------------------------------------------------------------------------
1 | This directory is used to store static files.
--------------------------------------------------------------------------------
/uliweb/contrib/soap/templates/readme.txt:
--------------------------------------------------------------------------------
1 | This directory is used to store template files.
--------------------------------------------------------------------------------
/uliweb/contrib/staticfiles/__init__.py:
--------------------------------------------------------------------------------
1 | from uliweb.core.SimpleFrame import expose
2 |
3 | def startup_installed(sender):
4 | url = sender.settings.GLOBAL.STATIC_URL.rstrip('/')
5 | expose('%s/' % url, static=True)(static)
6 |
7 | def prepare_default_env(sender, env):
8 | env['url_for_static'] = url_for_static
9 |
10 | def url_for_static(filename=None, **kwargs):
11 | from uliweb import settings, application
12 | from uliweb.core.SimpleFrame import get_url_adapter
13 | from urlparse import urlparse, urlunparse, urljoin
14 | import urllib
15 |
16 | domain = application.domains.get('static', {})
17 |
18 | #add STATIC_VER support
19 | ver = settings.GLOBAL.STATIC_VER
20 | if ver:
21 | kwargs['ver'] = ver
22 |
23 | #process external flag
24 | external = kwargs.pop('_external', False)
25 | if not external:
26 | external = domain.get('display', False)
27 |
28 | #process url prefix with '/'
29 | if filename.startswith('/'):
30 | if filename.endswith('/'):
31 | filename = filename[:-1]
32 | if kwargs:
33 | filename += '?' + urllib.urlencode(kwargs)
34 | if external:
35 | return urljoin(domain.get('domain', ''), filename)
36 | return filename
37 |
38 | #process url has already domain info
39 | r = urlparse(filename)
40 | if r.scheme or r.netloc:
41 | x = list(r)
42 | if kwargs:
43 | x[4] = urllib.urlencode(kwargs)
44 | return urlunparse(x)
45 | else:
46 | return filename
47 |
48 | kwargs['filename'] = filename
49 | url_adapter = get_url_adapter('static')
50 | return url_adapter.build('uliweb.contrib.staticfiles.static',
51 | kwargs, force_external=external)
52 |
53 | def static(filename):
54 | pass
55 |
56 |
--------------------------------------------------------------------------------
/uliweb/contrib/staticfiles/conf.py:
--------------------------------------------------------------------------------
1 | from uliweb.form import *
2 |
3 | class ManageForm(Form):
4 | static_url = StringField(label='Static URL prefix:', required=True, key='wsgi_middleware_staticfiles/STATIC_URL')
--------------------------------------------------------------------------------
/uliweb/contrib/staticfiles/info.ini:
--------------------------------------------------------------------------------
1 | [info]
2 | catalog = "System Apps"
3 | title = "Static Files Serving App"
4 | description = """Can be used to providing static file serving, for example:
5 |
6 | * image view
7 | * file download
8 | """
--------------------------------------------------------------------------------
/uliweb/contrib/staticfiles/settings.ini:
--------------------------------------------------------------------------------
1 | [WSGI_MIDDLEWARES]
2 | staticfiles = 'uliweb.contrib.staticfiles.wsgi_staticfiles.StaticFilesMiddleware', {'STATIC_URL':'/static/'}
3 |
4 | [GLOBAL]
5 | STATIC_VER = None
6 | #DOMAIN should format like http://xxx.yyy
7 | STATIC_DOMAIN = ''
8 | STATIC_DOMAIN_SHOW = False
9 | STATIC_URL = '/static'
10 |
11 | [STATICFILES]
12 | STATIC_FOLDER = ''
13 |
14 | [FUNCTIONS]
15 | url_for_static = 'uliweb.contrib.staticfiles.url_for_static'
16 |
17 | [BINDS]
18 | staticfiles.startup_installed = 'startup_installed', 'uliweb.contrib.staticfiles.startup_installed'
19 | staticfiles.prepare_default_env = 'prepare_default_env', 'uliweb.contrib.staticfiles.prepare_default_env'
--------------------------------------------------------------------------------
/uliweb/contrib/tables/__init__.py:
--------------------------------------------------------------------------------
1 | from uliweb import functions
2 |
3 | __tables__ = {}
4 |
5 | def get_table(tablename):
6 | Tables = functions.get_model('tables')
7 |
8 | if tablename not in __tables__:
9 | table = Tables.get_table(tablename)
10 | __tables__[tablename] = table
11 | return table
12 | else:
13 | return __tables__[tablename]
--------------------------------------------------------------------------------
/uliweb/contrib/tables/conf.py:
--------------------------------------------------------------------------------
1 | from uliweb.form import *
2 |
3 | #class ManageForm(Form):
4 | # debug_log = BooleanField(label='Debug Log:', key='ORM/DEBUG_LOG')
5 | # auto_create = BooleanField(label='Auto Create Table:', key='ORM/AUTO_CREATE')
6 | # connection = StringField(label='Database Connection String:', required=True, key='ORM/CONNECTION')
7 |
--------------------------------------------------------------------------------
/uliweb/contrib/tables/dbinit.py:
--------------------------------------------------------------------------------
1 | from uliweb.orm import get_model, __models__
2 |
3 | Tables = get_model('tables')
4 | for tablename, v in __models__.iteritems():
5 | table = get_model(tablename)
6 | if hasattr(table, '__verbose_name__'):
7 | verbose_name = getattr(table, '__verbose_name__')
8 | else:
9 | verbose_name = tablename
10 |
11 | obj = Tables.get(Tables.c.table_name == tablename)
12 | if obj:
13 | obj.verbose_name = verbose_name
14 | else:
15 | obj = Tables(table_name=tablename, verbose_name=verbose_name)
16 | obj.save()
17 | print 'Process %s...[%s]' % (tablename, verbose_name)
--------------------------------------------------------------------------------
/uliweb/contrib/tables/info.ini:
--------------------------------------------------------------------------------
1 | [info]
2 | catalog = ''
3 | title = ''
4 | description = ''
5 | icon = ''
6 | author = ''
7 | version = ''
8 | homepage = ''
9 |
--------------------------------------------------------------------------------
/uliweb/contrib/tables/models.py:
--------------------------------------------------------------------------------
1 | #coding=utf-8
2 |
3 | from uliweb.orm import Model, Field, get_model as _get_model, NotFound
4 | from uliweb.utils.common import get_var
5 | import datetime
6 |
7 | class Tables(Model):
8 | table_name =Field(str, max_length=40, verbose_name="表名", required=True)
9 | verbose_name = Field(str, max_length=255, verbose_name="说明")
10 |
11 | @classmethod
12 | def get_table(cls, tablename):
13 | obj = cls.get(cls.c.table_name == tablename)
14 | if not obj:
15 | obj = Tables(table_name=tablename, verbose_name=tablename)
16 | obj.save()
17 | return obj
18 |
19 | @classmethod
20 | def get_model(cls, table):
21 | if isinstance(table, int):
22 | obj = cls.get(cls.c.id == table)
23 | else:
24 | obj = cls.get(cls.c.table_name == table)
25 | if obj:
26 | return _get_model(obj.table_name)
27 | else:
28 | raise NotFound("Can't find model of table [%s]" % str(table))
29 |
30 | @classmethod
31 | def get_tablename(cls, table_id):
32 | obj = cls.get(cls.c.id == table)
33 | if obj:
34 | return obj.table_name
35 | else:
36 | raise NotFound("Can't find table according to table_id [%d]" % table_id)
37 |
38 | @classmethod
39 | def get_object(cls, table, object_id):
40 | model = cls.get_model(table)
41 | if not model:
42 | raise NotFound('Table %r is not existed' % table)
43 | return model.get(object_id)
44 |
45 | def __unicode__(self):
46 | if self.table_name == self.verbose_name:
47 | return self.table_name
48 | else:
49 | return u"%s(%s)" % (self.table_name, self.verbose_name)
50 |
--------------------------------------------------------------------------------
/uliweb/contrib/tables/settings.ini:
--------------------------------------------------------------------------------
1 | [MODELS]
2 | tables = 'uliweb.contrib.tables.models.Tables'
3 |
4 | [FUNCTIONS]
5 | get_table = 'uliweb.contrib.tables.get_table'
6 |
--------------------------------------------------------------------------------
/uliweb/contrib/template/__init__.py:
--------------------------------------------------------------------------------
1 | def startup_installed(sender):
2 | from uliweb.core import template
3 | from .tags import link, use, htmlmerge
4 |
5 | template.default_namespace['_tag_link'] = link
6 | template.default_namespace['_tag_use'] = use
7 | template.default_namespace['_tag_htmlmerge'] = htmlmerge
8 |
9 | def init_static_combine():
10 | """
11 | Process static combine, create md5 key according each static filename
12 | """
13 | from uliweb import settings
14 | from hashlib import md5
15 | import os
16 |
17 | d = {}
18 | if settings.get_var('STATIC_COMBINE_CONFIG/enable', False):
19 | for k, v in settings.get('STATIC_COMBINE', {}).items():
20 | key = '_cmb_'+md5(''.join(v)).hexdigest()+os.path.splitext(v[0])[1]
21 | d[key] = v
22 |
23 | return d
--------------------------------------------------------------------------------
/uliweb/contrib/template/conf.py:
--------------------------------------------------------------------------------
1 | from uliweb.form import *
2 |
3 | class ManageForm(Form):
4 | use_template_temp_dir = BooleanField(label='Use template temp dir:', key='TEMPLATE/USE_TEMPLATE_TEMP_DIR')
5 | template_temp_dir = StringField(label='Template temp dir:', required=True, key='TEMPLATE/TEMPLATE_TEMP_DIR')
--------------------------------------------------------------------------------
/uliweb/contrib/template/config.ini:
--------------------------------------------------------------------------------
1 | [DEPENDS]
2 | REQUIRED_APPS = [
3 | 'uliweb.contrib.staticfiles',
4 | ]
5 |
--------------------------------------------------------------------------------
/uliweb/contrib/template/info.ini:
--------------------------------------------------------------------------------
1 | [info]
2 | catalog = "System Apps"
3 | title = "Template Enhance App"
4 | description = """Provide use and link tag, user can use it to support
5 | html plugins.
6 | """
--------------------------------------------------------------------------------
/uliweb/contrib/template/settings.ini:
--------------------------------------------------------------------------------
1 | [BINDS]
2 | ulayout.startup_installed = 'startup_installed', 'uliweb.contrib.template.startup_installed'
3 |
4 | [STATIC_COMBINE]
5 |
6 | [STATIC_COMBINE_CONFIG]
7 | enable = False
8 | init_static_combine = '#{appname}.init_static_combine'
--------------------------------------------------------------------------------
/uliweb/contrib/timezone/__init__.py:
--------------------------------------------------------------------------------
1 | def startup_installed(sender):
2 | from uliweb.utils.date import set_timezone, set_local_timezone
3 |
4 | set_timezone(sender.settings.GLOBAL.TIME_ZONE)
5 | set_local_timezone(sender.settings.GLOBAL.LOCAL_TIME_ZONE)
--------------------------------------------------------------------------------
/uliweb/contrib/timezone/conf.py:
--------------------------------------------------------------------------------
1 | from uliweb.form import *
2 |
3 | #class ManageForm(Form):
4 | # debug_log = BooleanField(label='Debug Log:', key='ORM/DEBUG_LOG')
5 | # auto_create = BooleanField(label='Auto Create Table:', key='ORM/AUTO_CREATE')
6 | # connection = StringField(label='Database Connection String:', required=True, key='ORM/CONNECTION')
7 |
--------------------------------------------------------------------------------
/uliweb/contrib/timezone/info.ini:
--------------------------------------------------------------------------------
1 | [info]
2 | catalog = ''
3 | title = ''
4 | description = ''
5 | icon = ''
6 | author = ''
7 | version = ''
8 | homepage = ''
9 |
--------------------------------------------------------------------------------
/uliweb/contrib/timezone/settings.ini:
--------------------------------------------------------------------------------
1 | [BINDS]
2 | timezone.startup_installed = 'startup_installed', 'uliweb.contrib.timezone.startup_installed'
--------------------------------------------------------------------------------
/uliweb/contrib/upload/conf.py:
--------------------------------------------------------------------------------
1 | from uliweb.form import *
2 |
3 | class ManageForm(Form):
4 | to_path = StringField(label='Save Files to:', key='UPLOAD/TO_PATH')
5 | url_suffix = StringField(label='Uploaded files url suffix:', key='UPLOAD/URL_SUFFIX')
6 | buffer_size = IntField(label='Transfering buffer size:', key='UPLOAD/BUFFER_SIZE')
7 |
--------------------------------------------------------------------------------
/uliweb/contrib/upload/info.ini:
--------------------------------------------------------------------------------
1 | [info]
2 | catalog = "System Apps"
3 | title = "Upload Files App"
4 | description = """You can use it to easily upload files and show the link of them.
5 | """
--------------------------------------------------------------------------------
/uliweb/contrib/upload/settings.ini:
--------------------------------------------------------------------------------
1 | [UPLOAD]
2 | TO_PATH = './uploads'
3 | BUFFER_SIZE = 4096
4 | FILENAME_CONVERTER =
5 | BACKEND =
6 |
7 | #X-Sendfile type: nginx, apache
8 | X_SENDFILE = None
9 |
10 | #if not set, then will be set a default value that according to X_SENDFILE
11 | #nginx will be 'X-Accel-Redirect'
12 | #apache will be 'X-Sendfile'
13 | X_HEADER_NAME = ''
14 | X_FILE_PREFIX = '/files'
15 |
16 | [EXPOSES]
17 | file_serving = '/uploads/', 'uliweb.contrib.upload.file_serving'
18 |
19 | [FUNCTIONS]
20 | get_filename = 'uliweb.contrib.upload.get_filename'
21 | save_file = 'uliweb.contrib.upload.save_file'
22 | save_file_field = 'uliweb.contrib.upload.save_file_field'
23 | save_image_field = 'uliweb.contrib.upload.save_image_field'
24 | delete_filename = 'uliweb.contrib.upload.delete_filename'
25 | get_url = 'uliweb.contrib.upload.get_url'
26 | get_href = 'uliweb.contrib.upload.get_href'
27 | download = 'uliweb.contrib.upload.download'
28 | filename_convert = 'uliweb.contrib.upload.filename_convert'
29 | get_fileserving = 'uliweb.contrib.upload.get_backend'
30 |
31 | [MIME_TYPES]
32 | .svg = 'image/svg+xml'
33 |
34 | [BINDS]
35 | upload.after_init_apps = 'after_init_apps', 'uliweb.contrib.upload.after_init_apps'
36 |
--------------------------------------------------------------------------------
/uliweb/contrib/xmlrpc/__init__.py:
--------------------------------------------------------------------------------
1 | import inspect
2 | from functools import partial
3 |
4 | __xmlrpc_functions__ = {}
5 |
6 | class Rule(object):
7 | pass
8 |
9 | def xmlrpc(func, name=None):
10 | global __xmlrpc_functions__
11 |
12 | if isinstance(func, str):
13 | return partial(xmlrpc, name=func)
14 |
15 | if inspect.isfunction(func):
16 | f_name = func.__name__
17 | if name:
18 | f_name = name
19 | rule = Rule()
20 | rule.endpoint = '.'.join([func.__module__, func.__name__])
21 | rule.rule = rule.endpoint
22 | __xmlrpc_functions__[f_name] = rule
23 | func.xmlrpc_endpoint = (f_name, rule.endpoint)
24 | elif inspect.isclass(func):
25 | if not name:
26 | name = func.__name__
27 | for _name in dir(func):
28 | f = getattr(func, _name)
29 | if (inspect.ismethod(f) or inspect.isfunction(f)) and not _name.startswith('_'):
30 | f_name = name + '.' + f.__name__
31 | endpoint = '.'.join([func.__module__, func.__name__, _name])
32 | rule = Rule()
33 | rule.endpoint = rule.rule = endpoint
34 | if hasattr(f, 'xmlrpc_endpoint'):
35 | #the method has already been decorate by xmlrpc
36 | _n, _e = f.xmlrpc_endpoint
37 | __xmlrpc_functions__[name + '.' + _n] = rule
38 | del __xmlrpc_functions__[_n]
39 | else:
40 | __xmlrpc_functions__[f_name] = rule
41 | else:
42 | raise Exception("Can't support this type [%r]" % func)
43 | return func
44 |
45 | if __name__ == '__main__':
46 | @xmlrpc
47 | def f(name):
48 | print (name)
49 |
50 | print (__xmlrpc_functions__)
51 |
52 | @xmlrpc('B')
53 | class A(object):
54 | def p(self):
55 | print ('ppp')
56 |
57 | @xmlrpc('test')
58 | def t(self):
59 | print ('ttt')
60 |
61 | print (__xmlrpc_functions__)
62 |
--------------------------------------------------------------------------------
/uliweb/contrib/xmlrpc/conf.py:
--------------------------------------------------------------------------------
1 | from uliweb.form import *
2 |
3 | #class ManageForm(Form):
4 | # debug_log = BooleanField(label='Debug Log:', key='ORM/DEBUG_LOG')
5 | # auto_create = BooleanField(label='Auto Create Table:', key='ORM/AUTO_CREATE')
6 | # connection = StringField(label='Database Connection String:', required=True, key='ORM/CONNECTION')
7 |
--------------------------------------------------------------------------------
/uliweb/contrib/xmlrpc/info.ini:
--------------------------------------------------------------------------------
1 | [info]
2 | catalog = ''
3 | title = ''
4 | description = ''
5 | icon = ''
6 | author = ''
7 | version = ''
8 | homepage = ''
9 |
--------------------------------------------------------------------------------
/uliweb/contrib/xmlrpc/settings.ini:
--------------------------------------------------------------------------------
1 | [FUNCTIONS]
2 | xmlrpc = 'uliweb.contrib.xmlrpc.xmlrpc'
3 |
4 | [EXPOSES]
5 | xmlrpc = '/XMLRPC', 'uliweb.contrib.xmlrpc.views.xmlrpc'
6 |
--------------------------------------------------------------------------------
/uliweb/contrib/xmlrpc/views.py:
--------------------------------------------------------------------------------
1 | def _wrap_result(handler, result, request, response, env):
2 | return result
3 |
4 | def xmlrpc():
5 | import uliweb.contrib.xmlrpc as rpc
6 | import xmlrpclib
7 | from werkzeug import Response
8 | from uliweb.utils.common import log
9 | from uliweb import application as app, response
10 |
11 | p, m = xmlrpclib.loads(request.data)
12 | try:
13 | f = rpc.__xmlrpc_functions__.get(m)
14 | if f:
15 | mod, handler_cls, handler = app.prepare_request(request, f)
16 | result = app.call_view(mod, handler_cls, handler, request, response, _wrap_result, args=p)
17 | xml = xmlrpclib.dumps((result,), methodresponse=1)
18 | else:
19 | xml = xmlrpclib.dumps(xmlrpclib.Fault(-32400, 'system error: Cannot find or call %s' % m), methodresponse=1)
20 | log.debug('xmlrpc error: Cannot find or call %s' % m)
21 | except Exception as e:
22 | xml = xmlrpclib.dumps(xmlrpclib.Fault(-32400, 'system error: %s' % e), methodresponse=1)
23 | log.exception('xmlrpc error')
24 | response = Response(xml, content_type='text/xml; charset=utf-8')
25 | return response
--------------------------------------------------------------------------------
/uliweb/core/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/limodou/uliweb/8bc827fa6bf7bf58aa8136b6c920fe2650c52422/uliweb/core/__init__.py
--------------------------------------------------------------------------------
/uliweb/core/default.html:
--------------------------------------------------------------------------------
1 | Default Template
2 | This page is created from default template, because Uliweb can't
3 | find a matched template "{{=response.template}}".
4 | {{import pprint
5 | from uliweb.utils.textconvert import text2html}}
6 | {{<
9 | function SetCookie( name, value, expires, path, domain, secure )
10 | {
11 | var today = new Date();
12 | today.setTime( today.getTime() );
13 | path='/';
14 | if ( expires )
15 | {
16 | expires = expires * 1000 * 60 * 60 * 24;
17 | }
18 | var expires_date = new Date( today.getTime() + (expires) );
19 |
20 | document.cookie = name + "=" +escape( value ) +
21 | ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
22 | ( ( path ) ? ";path=" + path : "" ) +
23 | ( ( domain ) ? ";domain=" + domain : "" ) +
24 | ( ( secure ) ? ";secure" : "" );
25 | window.location.reload();
26 | }
27 | ''')
28 | s.append('''''')
43 | return ''.join(s)
44 |
--------------------------------------------------------------------------------
/uliweb/i18n/lazystr.py:
--------------------------------------------------------------------------------
1 | def lazy(func):
2 | def f(message):
3 | return LazyString(func, message)
4 | return f
5 |
6 | class LazyString(object):
7 | """
8 | >>> from uliweb.i18n import gettext_lazy as _
9 | >>> x = _('Hello')
10 | >>> print repr(x)
11 | """
12 | def __init__(self, func, message):
13 | self._func = func
14 | self.msg = message
15 | self._format = []
16 |
17 | def __unicode__(self):
18 | if not self.msg:
19 | return ''
20 | value = self.getvalue()
21 | if isinstance(value, unicode):
22 | return value
23 | else:
24 | return unicode(self.getvalue(), 'utf-8')
25 |
26 | def __str__(self):
27 | if not self.msg:
28 | return ''
29 | value = self.getvalue()
30 | if isinstance(value, unicode):
31 | return value.encode('utf-8')
32 | else:
33 | return str(value)
34 |
35 | def format(self, *args, **kwargs):
36 | self._format.append((args, kwargs))
37 | return self
38 |
39 | def getvalue(self):
40 | v = self._func(self.msg)
41 | for args, kwargs in self._format:
42 | v = v.format(*args, **kwargs)
43 | return v
44 |
45 | def __repr__(self):
46 | return "%s_lazy(%r)" % (self._func.__name__, self.msg)
47 |
48 | def __add__(self, obj):
49 | return self.getvalue() + obj
50 |
51 | def __radd__(self, obj):
52 | return obj + self.getvalue()
53 |
54 | def encode(self, encoding):
55 | return self.getvalue().encode(encoding)
56 |
57 | def split(self, *args, **kwargs):
58 | return self.getvalue().split(*args, **kwargs)
59 |
60 | # def __getattr__(self, name):
61 | # return getattr(self.getvalue(), name)
62 |
--------------------------------------------------------------------------------
/uliweb/i18n/po_template.ini:
--------------------------------------------------------------------------------
1 | [I18N]
2 | First_Author = 'FIRST AUTHOR '
3 | Project_Id_Version = 'PACKAGE VERSION'
4 | Last_Translator = 'FULL NAME '
5 | Language_Team = 'LANGUAGE '
6 | Content_Type_Charset = 'utf-8'
7 | Content_Transfer_Encoding = '8bit'
8 | Plural_Forms = 'nplurals=1; plural=0;'
--------------------------------------------------------------------------------
/uliweb/lib/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/limodou/uliweb/8bc827fa6bf7bf58aa8136b6c920fe2650c52422/uliweb/lib/__init__.py
--------------------------------------------------------------------------------
/uliweb/lib/colorama/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Copyright (c) 2010 Jonathan Hartley
2 |
3 | Released under the New BSD license (reproduced below), or alternatively you may
4 | use this software under any OSI approved open source license such as those at
5 | http://opensource.org/licenses/alphabetical
6 |
7 | All rights reserved.
8 |
9 | Redistribution and use in source and binary forms, with or without
10 | modification, are permitted provided that the following conditions are met:
11 |
12 | * Redistributions of source code must retain the above copyright notice, this
13 | list of conditions and the following disclaimer.
14 |
15 | * Redistributions in binary form must reproduce the above copyright notice,
16 | this list of conditions and the following disclaimer in the documentation
17 | and/or other materials provided with the distribution.
18 |
19 | * Neither the name(s) of the copyright holders, nor those of its contributors
20 | may be used to endorse or promote products derived from this software without
21 | specific prior written permission.
22 |
23 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
24 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
27 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
29 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
30 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 |
34 |
--------------------------------------------------------------------------------
/uliweb/lib/colorama/__init__.py:
--------------------------------------------------------------------------------
1 | from .initialise import init, deinit, reinit
2 | from .ansi import Fore, Back, Style
3 | from .ansitowin32 import AnsiToWin32
4 |
5 | VERSION = '0.2.5'
6 |
7 |
--------------------------------------------------------------------------------
/uliweb/lib/colorama/ansi.py:
--------------------------------------------------------------------------------
1 | '''
2 | This module generates ANSI character codes to printing colors to terminals.
3 | See: http://en.wikipedia.org/wiki/ANSI_escape_code
4 | '''
5 |
6 | CSI = '\033['
7 |
8 | def code_to_chars(code):
9 | return CSI + str(code) + 'm'
10 |
11 | class AnsiCodes(object):
12 | def __init__(self, codes):
13 | for name in dir(codes):
14 | if not name.startswith('_'):
15 | value = getattr(codes, name)
16 | setattr(self, name, code_to_chars(value))
17 |
18 | class AnsiFore:
19 | BLACK = 30
20 | RED = 31
21 | GREEN = 32
22 | YELLOW = 33
23 | BLUE = 34
24 | MAGENTA = 35
25 | CYAN = 36
26 | WHITE = 37
27 | RESET = 39
28 |
29 | class AnsiBack:
30 | BLACK = 40
31 | RED = 41
32 | GREEN = 42
33 | YELLOW = 43
34 | BLUE = 44
35 | MAGENTA = 45
36 | CYAN = 46
37 | WHITE = 47
38 | RESET = 49
39 |
40 | class AnsiStyle:
41 | BRIGHT = 1
42 | DIM = 2
43 | NORMAL = 22
44 | RESET_ALL = 0
45 |
46 | Fore = AnsiCodes( AnsiFore )
47 | Back = AnsiCodes( AnsiBack )
48 | Style = AnsiCodes( AnsiStyle )
49 |
50 |
--------------------------------------------------------------------------------
/uliweb/lib/colorama/initialise.py:
--------------------------------------------------------------------------------
1 | import atexit
2 | import sys
3 |
4 | from .ansitowin32 import AnsiToWin32
5 |
6 |
7 | orig_stdout = sys.stdout
8 | orig_stderr = sys.stderr
9 |
10 | wrapped_stdout = sys.stdout
11 | wrapped_stderr = sys.stderr
12 |
13 | atexit_done = False
14 |
15 |
16 | def reset_all():
17 | AnsiToWin32(orig_stdout).reset_all()
18 |
19 |
20 | def init(autoreset=False, convert=None, strip=None, wrap=True):
21 |
22 | if not wrap and any([autoreset, convert, strip]):
23 | raise ValueError('wrap=False conflicts with any other arg=True')
24 |
25 | global wrapped_stdout, wrapped_stderr
26 | sys.stdout = wrapped_stdout = \
27 | wrap_stream(orig_stdout, convert, strip, autoreset, wrap)
28 | sys.stderr = wrapped_stderr = \
29 | wrap_stream(orig_stderr, convert, strip, autoreset, wrap)
30 |
31 | global atexit_done
32 | if not atexit_done:
33 | atexit.register(reset_all)
34 | atexit_done = True
35 |
36 |
37 | def deinit():
38 | sys.stdout = orig_stdout
39 | sys.stderr = orig_stderr
40 |
41 |
42 | def reinit():
43 | sys.stdout = wrapped_stdout
44 | sys.stderr = wrapped_stdout
45 |
46 |
47 | def wrap_stream(stream, convert, strip, autoreset, wrap):
48 | if wrap:
49 | wrapper = AnsiToWin32(stream,
50 | convert=convert, strip=strip, autoreset=autoreset)
51 | if wrapper.should_wrap():
52 | stream = wrapper.stream
53 | return stream
54 |
55 |
56 |
--------------------------------------------------------------------------------
/uliweb/lib/rcssmin/MANIFEST:
--------------------------------------------------------------------------------
1 | LICENSE
2 | MANIFEST
3 | PKG-INFO
4 | README
5 | _setup/__init__.py
6 | _setup/include/cext.h
7 | _setup/py2/__init__.py
8 | _setup/py2/commands.py
9 | _setup/py2/data.py
10 | _setup/py2/dist.py
11 | _setup/py2/ext.py
12 | _setup/py2/setup.py
13 | _setup/py2/shell.py
14 | _setup/py2/util.py
15 | _setup/py3/__init__.py
16 | _setup/py3/commands.py
17 | _setup/py3/data.py
18 | _setup/py3/dist.py
19 | _setup/py3/ext.py
20 | _setup/py3/setup.py
21 | _setup/py3/shell.py
22 | _setup/py3/util.py
23 | docs/CHANGES
24 | docs/CLASSIFIERS
25 | docs/DESCRIPTION
26 | docs/PROVIDES
27 | docs/SUMMARY
28 | docs/apidoc/api-objects.txt
29 | docs/apidoc/crarr.png
30 | docs/apidoc/epydoc.css
31 | docs/apidoc/epydoc.js
32 | docs/apidoc/help.html
33 | docs/apidoc/identifier-index.html
34 | docs/apidoc/index.html
35 | docs/apidoc/module-tree.html
36 | docs/apidoc/rcssmin-module.html
37 | docs/apidoc/rcssmin-pysrc.html
38 | docs/apidoc/redirect.html
39 | package.cfg
40 | rcssmin.c
41 | rcssmin.py
42 | setup.py
43 |
--------------------------------------------------------------------------------
/uliweb/lib/rcssmin/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/limodou/uliweb/8bc827fa6bf7bf58aa8136b6c920fe2650c52422/uliweb/lib/rcssmin/__init__.py
--------------------------------------------------------------------------------
/uliweb/lib/rjsmin/MANIFEST:
--------------------------------------------------------------------------------
1 | LICENSE
2 | MANIFEST
3 | PKG-INFO
4 | README
5 | _setup/__init__.py
6 | _setup/include/cext.h
7 | _setup/py2/__init__.py
8 | _setup/py2/commands.py
9 | _setup/py2/data.py
10 | _setup/py2/dist.py
11 | _setup/py2/ext.py
12 | _setup/py2/setup.py
13 | _setup/py2/shell.py
14 | _setup/py2/util.py
15 | _setup/py3/__init__.py
16 | _setup/py3/commands.py
17 | _setup/py3/data.py
18 | _setup/py3/dist.py
19 | _setup/py3/ext.py
20 | _setup/py3/setup.py
21 | _setup/py3/shell.py
22 | _setup/py3/util.py
23 | bench
24 | bench.py
25 | bench/__init__.py
26 | bench/apiviewer.js
27 | bench/jquery-1.7.1.js
28 | bench/jsmin.c
29 | bench/jsmin.py
30 | bench/jsmin_2_0_2.py
31 | bench/jsmin_playground.py
32 | bench/knockout-2.0.0.js
33 | bench/markermanager.js
34 | docs/BENCHMARKS
35 | docs/CHANGES
36 | docs/CLASSIFIERS
37 | docs/DESCRIPTION
38 | docs/PROVIDES
39 | docs/SUMMARY
40 | docs/apidoc/api-objects.txt
41 | docs/apidoc/crarr.png
42 | docs/apidoc/epydoc.css
43 | docs/apidoc/epydoc.js
44 | docs/apidoc/help.html
45 | docs/apidoc/identifier-index.html
46 | docs/apidoc/index.html
47 | docs/apidoc/module-tree.html
48 | docs/apidoc/redirect.html
49 | docs/apidoc/rjsmin-module.html
50 | docs/apidoc/rjsmin-pysrc.html
51 | package.cfg
52 | rjsmin.c
53 | rjsmin.py
54 | setup.py
55 |
--------------------------------------------------------------------------------
/uliweb/lib/rjsmin/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/limodou/uliweb/8bc827fa6bf7bf58aa8136b6c920fe2650c52422/uliweb/lib/rjsmin/__init__.py
--------------------------------------------------------------------------------
/uliweb/lib/werkzeug/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2006 by the respective authors (see AUTHORS file).
2 | All rights reserved.
3 |
4 | Redistribution and use in source and binary forms, with or without
5 | modification, are permitted provided that the following conditions are
6 | met:
7 |
8 | * Redistributions of source code must retain the above copyright
9 | notice, this list of conditions and the following disclaimer.
10 |
11 | * Redistributions in binary form must reproduce the above
12 | copyright notice, this list of conditions and the following
13 | disclaimer in the documentation and/or other materials provided
14 | with the distribution.
15 |
16 | * The names of the contributors may not be used to endorse or
17 | promote products derived from this software without specific
18 | prior written permission.
19 |
20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 |
--------------------------------------------------------------------------------
/uliweb/lib/werkzeug/contrib/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | werkzeug.contrib
4 | ~~~~~~~~~~~~~~~~
5 |
6 | Contains user-submitted code that other users may find useful, but which
7 | is not part of the Werkzeug core. Anyone can write code for inclusion in
8 | the `contrib` package. All modules in this package are distributed as an
9 | add-on library and thus are not part of Werkzeug itself.
10 |
11 | This file itself is mostly for informational purposes and to tell the
12 | Python interpreter that `contrib` is a package.
13 |
14 | :copyright: (c) 2013 by the Werkzeug Team, see AUTHORS for more details.
15 | :license: BSD, see LICENSE for more details.
16 | """
17 |
--------------------------------------------------------------------------------
/uliweb/lib/werkzeug/contrib/limiter.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | werkzeug.contrib.limiter
4 | ~~~~~~~~~~~~~~~~~~~~~~~~
5 |
6 | A middleware that limits incoming data. This works around problems with
7 | Trac_ or Django_ because those directly stream into the memory.
8 |
9 | .. _Trac: http://trac.edgewall.org/
10 | .. _Django: http://www.djangoproject.com/
11 |
12 | :copyright: (c) 2013 by the Werkzeug Team, see AUTHORS for more details.
13 | :license: BSD, see LICENSE for more details.
14 | """
15 | from warnings import warn
16 |
17 | from werkzeug.wsgi import LimitedStream
18 |
19 |
20 | class StreamLimitMiddleware(object):
21 | """Limits the input stream to a given number of bytes. This is useful if
22 | you have a WSGI application that reads form data into memory (django for
23 | example) and you don't want users to harm the server by uploading tons of
24 | data.
25 |
26 | Default is 10MB
27 |
28 | .. versionchanged:: 0.9
29 | Deprecated middleware.
30 | """
31 |
32 | def __init__(self, app, maximum_size=1024 * 1024 * 10):
33 | warn(DeprecationWarning('This middleware is deprecated'))
34 | self.app = app
35 | self.maximum_size = maximum_size
36 |
37 | def __call__(self, environ, start_response):
38 | limit = min(self.maximum_size, int(environ.get('CONTENT_LENGTH') or 0))
39 | environ['wsgi.input'] = LimitedStream(environ['wsgi.input'], limit)
40 | return self.app(environ, start_response)
41 |
--------------------------------------------------------------------------------
/uliweb/lib/werkzeug/contrib/testtools.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | werkzeug.contrib.testtools
4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~
5 |
6 | This module implements extended wrappers for simplified testing.
7 |
8 | `TestResponse`
9 | A response wrapper which adds various cached attributes for
10 | simplified assertions on various content types.
11 |
12 | :copyright: (c) 2013 by the Werkzeug Team, see AUTHORS for more details.
13 | :license: BSD, see LICENSE for more details.
14 | """
15 | from werkzeug.utils import cached_property, import_string
16 | from werkzeug.wrappers import Response
17 |
18 | from warnings import warn
19 | warn(DeprecationWarning('werkzeug.contrib.testtools is deprecated and '
20 | 'will be removed with Werkzeug 1.0'))
21 |
22 |
23 | class ContentAccessors(object):
24 | """
25 | A mixin class for response objects that provides a couple of useful
26 | accessors for unittesting.
27 | """
28 |
29 | def xml(self):
30 | """Get an etree if possible."""
31 | if 'xml' not in self.mimetype:
32 | raise AttributeError(
33 | 'Not a XML response (Content-Type: %s)'
34 | % self.mimetype)
35 | for module in ['xml.etree.ElementTree', 'ElementTree',
36 | 'elementtree.ElementTree']:
37 | etree = import_string(module, silent=True)
38 | if etree is not None:
39 | return etree.XML(self.body)
40 | raise RuntimeError('You must have ElementTree installed '
41 | 'to use TestResponse.xml')
42 | xml = cached_property(xml)
43 |
44 | def lxml(self):
45 | """Get an lxml etree if possible."""
46 | if ('html' not in self.mimetype and 'xml' not in self.mimetype):
47 | raise AttributeError('Not an HTML/XML response')
48 | from lxml import etree
49 | try:
50 | from lxml.html import fromstring
51 | except ImportError:
52 | fromstring = etree.HTML
53 | if self.mimetype=='text/html':
54 | return fromstring(self.data)
55 | return etree.XML(self.data)
56 | lxml = cached_property(lxml)
57 |
58 | def json(self):
59 | """Get the result of simplejson.loads if possible."""
60 | if 'json' not in self.mimetype:
61 | raise AttributeError('Not a JSON response')
62 | try:
63 | from simplejson import loads
64 | except ImportError:
65 | from json import loads
66 | return loads(self.data)
67 | json = cached_property(json)
68 |
69 |
70 | class TestResponse(Response, ContentAccessors):
71 | """Pass this to `werkzeug.test.Client` for easier unittesting."""
72 |
--------------------------------------------------------------------------------
/uliweb/lib/werkzeug/debug/render.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | werkzeug.debug.render
4 | ~~~~~~~~~~~~~~~~~~~~~
5 |
6 | Render the traceback debugging page.
7 |
8 | :copyright: 2007 by Georg Brandl, Armin Ronacher.
9 | :license: BSD, see LICENSE for more details.
10 | """
11 | import pprint
12 | from os.path import dirname, join
13 |
14 | #from werkzeug.templates import Template
15 | from uliweb.core.template import template_file
16 | from werkzeug.debug.util import Namespace
17 |
18 |
19 | def get_template(name):
20 | def render(vars, name=name):
21 | return template_file(join(dirname(__file__), 'shared', name), vars)
22 | return render
23 |
24 | def load_resource(res):
25 | try:
26 | f = file(join(dirname(__file__), 'shared', res))
27 | except IOError:
28 | return ''
29 | try:
30 | return f.read()
31 | finally:
32 | f.close()
33 |
34 |
35 | t_body = get_template('body.tmpl')
36 | t_codetable = get_template('codetable.tmpl')
37 | t_vartable = get_template('vartable.tmpl')
38 |
39 |
40 | def code_table(frame):
41 | lines = []
42 | lineno = frame['context_lineno']
43 | if lineno is not None:
44 | lineno += 1
45 | for l in frame['pre_context']:
46 | lines.append(Namespace(mode='pre', lineno=lineno, code=l))
47 | lineno += 1
48 | lines.append(Namespace(mode='cur', lineno=lineno,
49 | code=frame['context_line']))
50 | lineno += 1
51 | for l in frame['post_context']:
52 | lines.append(Namespace(mode='post', lineno=lineno, code=l))
53 | lineno += 1
54 | else:
55 | lines.append(Namespace(mode='cur', lineno=1,
56 | code='Sourcecode not available'))
57 |
58 | return t_codetable(dict(lines=lines))
59 |
60 |
61 | def var_table(var):
62 | def safe_pformat(x):
63 | try:
64 | lines = pprint.pformat(x).splitlines()
65 | except:
66 | return '?'
67 | tmp = []
68 | for line in lines:
69 | if len(line) > 79:
70 | line = line[:79] + '...'
71 | tmp.append(line)
72 | return '\n'.join(tmp)
73 |
74 | # dicts
75 | if isinstance(var, dict):
76 | value = var.items()
77 | if not value:
78 | typ = 'empty'
79 | else:
80 | typ = 'dict'
81 | value.sort()
82 | value = [(repr(key), safe_pformat(val)) for key, val in value]
83 |
84 | # lists
85 | elif isinstance(var, list):
86 | if not var:
87 | typ = 'empty'
88 | else:
89 | typ = 'list'
90 | value = [safe_pformat(item) for item in var]
91 |
92 | # others
93 | else:
94 | typ = 'simple'
95 | value = repr(var)
96 |
97 | return t_vartable(dict(type=typ, value=value))
98 |
99 |
100 | def debug_page(context):
101 | tc = context.to_dict()
102 | tc['var_table'] = var_table
103 | tc['code_table'] = code_table
104 | return t_body(tc)
105 |
--------------------------------------------------------------------------------
/uliweb/lib/werkzeug/debug/shared/codetable.tmpl:
--------------------------------------------------------------------------------
1 |
2 | {{for line in lines:}}
3 |
4 | {{=line.lineno}} |
5 | {{<
6 | |
7 | {{pass}}
8 |
9 |
--------------------------------------------------------------------------------
/uliweb/lib/werkzeug/debug/shared/vartable.tmpl:
--------------------------------------------------------------------------------
1 |
2 | {{ if type == 'empty': }}
3 | no data given |
4 | {{ elif type == 'simple': }}
5 | {{=value}} |
6 | {{ elif type == 'dict': }}
7 | Name | Value |
8 | {{ for key, item in value: }}
9 | {{=key}} | {{=item}} |
10 | {{ pass }}
11 | {{ elif type == 'list': }}
12 | {{ for item in value: }}
13 | {{=item}} |
14 | {{ pass }}
15 | {{ pass }}
16 |
17 |
--------------------------------------------------------------------------------
/uliweb/lib/werkzeug/debug/tbtools.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | werkzeug.debug.tbtools
4 | ~~~~~~~~~~~~~~~~~~~~~~
5 |
6 | This module provides various traceback related utility functions.
7 |
8 | :copyright: (c) 2010 by the Werkzeug Team, see AUTHORS for more details.
9 | :license: BSD.
10 | """
11 | import re
12 | import os
13 | import sys
14 | import inspect
15 | import traceback
16 | import codecs
17 | from tokenize import TokenError
18 |
19 | _coding_re = re.compile(r'coding[:=]\s*([-\w.]+)')
20 | _line_re = re.compile(r'^(.*?)$(?m)')
21 | _funcdef_re = re.compile(r'^(\s*def\s)|(.*(?Hello, Uliweb'
7 |
--------------------------------------------------------------------------------
/uliweb/template_files/command/command.tmpl:
--------------------------------------------------------------------------------
1 | class {{=name.title()}}Command({{if has_subcommands:}}CommandManager{{else:}}Command{{pass}}):
2 | #change the name to real command name, such as makeapp, makeproject, etc.
3 | name = '{{=name}}'
4 | #command line parameters definition
5 | option_list = (
6 | make_option('-d', '--demo', dest='demo', default=False, action='store_true',
7 | help='Demo command demo.'),
8 | )
9 | #help information
10 | help = ''
11 | #args information, used to display show the command usage message
12 | args = ''
13 | #if True, it'll check the current directory should has apps directory
14 | check_apps_dirs = True
15 | #if True, it'll check args parameters should be valid apps name
16 | check_apps = False
17 | #if True, it'll skip not predefined parameters in options_list, otherwise it'll
18 | #complain not the right parameters of the command, it'll used in subcommands or
19 | #passing extra parameters to a special command
20 | skip_options = {{=has_subcommands}}
21 | #if inherit the base class option_list, default True is inherit
22 | options_inherit = True
23 |
24 | {{if not has_subcommands:}}
25 | def handle(self, options, global_options, *args):
26 | print 'This is a demo of DemoCommand, you can enter: '
27 | print
28 | print ' uliweb help demo'
29 | print
30 | print 'to test this command'
31 | print
32 | print 'options=', options
33 | print 'global_options=', global_options
34 | print 'args=', args
35 | {{pass}}
36 |
37 | {{if has_subcommands:}}
38 | def get_commands(self, global_options):
39 | import {{=name}}_subcommands as subcommands
40 | cmds = get_commands(subcommands)
41 | return cmds
42 | {{pass}}
--------------------------------------------------------------------------------
/uliweb/template_files/command/command_head.tmpl:
--------------------------------------------------------------------------------
1 | from uliweb.core.commands import Command, CommandManager, get_commands
2 | from optparse import make_option
3 |
4 |
--------------------------------------------------------------------------------
/uliweb/template_files/config/nginx.conf:
--------------------------------------------------------------------------------
1 | #upstream uwsgicluster{
2 | # server 127.0.0.1:9001;
3 | # server 192.168.100.101:9001;
4 | # server 192.168.100.102:9001;
5 | # server 192.168.100.103:9001;
6 | # server 192.168.100.104:9001;
7 | #}
8 |
9 | server {
10 | listen {{=port}};
11 | #server_name $hostname;
12 | #access_log /srv/www/example.com/logs/access.log;
13 | #error_log/srv/www/example.com/logs/error.log;
14 |
15 | location ~ ^/static/ {
16 | root {{=static}};
17 | access_log off;
18 | }
19 |
20 | location / {
21 | include uwsgi_params;
22 | uwsgi_param UWSGI_SCHEME $scheme;
23 | uwsgi_param SERVER_SOFTWARE nginx/$nginx_version;
24 |
25 | uwsgi_pass unix:///tmp/{{=project}}.sock;
26 |
27 | #uwsgi_pass 127.0.0.1:9001
28 |
29 | #uwsgi_pass uwsgicluster
30 |
31 | #proxy_pass http://localhost:8000;
32 |
33 | #proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
34 |
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/uliweb/template_files/config/nginx.ini:
--------------------------------------------------------------------------------
1 | [INPUT]
2 | port = '', 80
3 | static = 'static files directory:',
--------------------------------------------------------------------------------
/uliweb/template_files/config/supervisor.conf:
--------------------------------------------------------------------------------
1 | [program:{{=project}}]
2 | command = uwsgi
3 | --socket /tmp/{{=project}}.sock
4 | --harakiri 60
5 | --reaper
6 | --module wsgi_handler
7 | --processes 10
8 | --master{{if defined('python_path'):}}{{out.write(" --home %s\n" % python_path)}}{{pass}}
9 | --chmod-socket=666
10 | --limit-as 512
11 | --socket-timeout 5
12 | --max-requests 1000
13 | --reload-mercy 8
14 | --reload-on-as 384
15 | --reload-on-rss 192
16 | --no-orphans
17 | directory={{=project_dir}}
18 | stopsignal=QUIT
19 | autostart=true
20 | autorestart=true
21 | stdout_logfile=/tmp/{{=project}}.log
22 | redirect_stderr=true
23 | exitcodes=0,1,2
24 |
--------------------------------------------------------------------------------
/uliweb/template_files/config/supervisor.ini:
--------------------------------------------------------------------------------
1 | [INPUT]
2 | python_path =
3 |
--------------------------------------------------------------------------------
/uliweb/template_files/config/uwsgi.conf:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | sockfile=/tmp/{{=project}}.sock
4 | projectdir={{=project_dir}}
5 | logfile={{=log_dir}}/{{=project}}.log
6 |
7 |
8 | if [ $1 = start ];then
9 | psid=`ps aux|grep "uwsgi"|grep -v "grep"|wc -l`
10 | if [ $psid -gt 2 ];then
11 | echo "uwsgi is running!"
12 | exit 0
13 | else
14 | uwsgi -s $sockfile --chdir $projectdir -w wsgi_handler -p 10 -M -t 120 -T -C -d $logfile
15 | fi
16 | echo "Start uwsgi service [OK]"
17 | elif [ $1 = stop ];then
18 | killall -9 uwsgi
19 | echo "Stop uwsgi service [OK]"
20 | elif [ $1 = restart ];then
21 | killall -9 uwsgi
22 | uwsgi -s $sockfile --chdir $projectdir -w wsgi_handler -p 10 -M -t 120 -T -C -d $logfile
23 | echo "Restart uwsgi service [OK]"
24 | else
25 | echo "Usages: sh start.sh [start|stop|restart]"
26 | fi
27 |
--------------------------------------------------------------------------------
/uliweb/template_files/config/uwsgi.ini:
--------------------------------------------------------------------------------
1 | [INPUT]
2 | log_dir = 'logs output directory:',
--------------------------------------------------------------------------------
/uliweb/template_files/module/.gitignore.template:
--------------------------------------------------------------------------------
1 | *.pyc
2 | *.bak
3 | build
4 | dist
5 | *.egg-info
6 | .idea
7 | _git
--------------------------------------------------------------------------------
/uliweb/template_files/module/module/__init__.py:
--------------------------------------------------------------------------------
1 | __version__ = '0.1'
2 | __url__ = ''
3 | __author__ = ''
4 | __email__ = ''
--------------------------------------------------------------------------------
/uliweb/template_files/module/module/settings.ini:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/limodou/uliweb/8bc827fa6bf7bf58aa8136b6c920fe2650c52422/uliweb/template_files/module/module/settings.ini
--------------------------------------------------------------------------------
/uliweb/template_files/module/setup.py.template:
--------------------------------------------------------------------------------
1 | #coding=utf8
2 | __doc__ = """{{=module_name}}"""
3 |
4 | import re
5 | import os
6 |
7 | from setuptools import setup
8 |
9 | def fpath(name):
10 | return os.path.join(os.path.dirname(__file__), name)
11 |
12 |
13 | def read(fname, default=''):
14 | filename = fpath(fname)
15 | if os.path.exists(filename):
16 | return open(fpath(fname)).read()
17 | else:
18 | return default
19 |
20 |
21 | def desc():
22 | info = read('README.md', __doc__)
23 | return info + '\n\n' + read('doc/CHANGELOG.md')
24 |
25 | file_text = read(fpath('{{=module_name.replace('-', '_')}}/__init__.py'))
26 |
27 |
28 | def grep(attrname):
29 | pattern = r"{0}\s*=\s*'([^']*)'".format(attrname)
30 | strval, = re.findall(pattern, file_text)
31 | return strval
32 |
33 | setup(
34 | name='{{=module_name}}',
35 | version=grep('__version__'),
36 | url=grep('__url__'),
37 | license='BSD',
38 | author=grep('__author__'),
39 | author_email=grep('__email__'),
40 | description='{{=module_name}}',
41 | long_description=desc(),
42 | packages = ['{{=module_name.replace('-', '_')}}'],
43 | include_package_data=True,
44 | zip_safe=False,
45 | platforms='any',
46 | install_requires=[
47 | 'uliweb',
48 | ],
49 | classifiers=[
50 | 'Development Status :: 4 - Beta',
51 | 'Environment :: Web Environment',
52 | 'Intended Audience :: Developers',
53 | 'License :: OSI Approved :: BSD License',
54 | 'Operating System :: OS Independent',
55 | 'Programming Language :: Python',
56 | 'Topic :: Software Development :: Libraries :: Python Modules'
57 | ],
58 | )
--------------------------------------------------------------------------------
/uliweb/template_files/project/.gitignore.template:
--------------------------------------------------------------------------------
1 | *.pyc
2 | *.bak
3 | local_settings.ini
4 | build
5 | dist
6 | *.egg-info
7 | .idea
8 | _git
--------------------------------------------------------------------------------
/uliweb/template_files/project/README.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/limodou/uliweb/8bc827fa6bf7bf58aa8136b6c920fe2650c52422/uliweb/template_files/project/README.md
--------------------------------------------------------------------------------
/uliweb/template_files/project/apps/__init__.py:
--------------------------------------------------------------------------------
1 | __version__ = '0.1'
2 | __url__ = ''
3 | __author__ = ''
4 | __email__ = ''
--------------------------------------------------------------------------------
/uliweb/template_files/project/apps/local_settings.ini:
--------------------------------------------------------------------------------
1 | [GLOBAL]
2 | DEBUG = True
3 | DEBUG_CONSOLE = True
4 | DEBUG_TEMPLATE = False
--------------------------------------------------------------------------------
/uliweb/template_files/project/apps/settings.ini:
--------------------------------------------------------------------------------
1 | [GLOBAL]
2 | DEBUG = False
3 | DEBUG_CONSOLE = False
4 | DEBUG_TEMPLATE = False
5 |
6 | #INSTALLED_APPS = [
7 | # 'uliweb.contrib.staticfiles',
8 | # 'uliweb.contrib.template',
9 | # 'uliweb.contrib.upload',
10 | # 'uliweb.contrib.orm',
11 | # 'uliweb.contrib.session',
12 | # 'uliweb.contrib.cache',
13 | # 'uliweb.contrib.auth',
14 | # 'uliweb.contrib.i18n',
15 | # 'uliweb.contrib.flashmessage',
16 | # ]
--------------------------------------------------------------------------------
/uliweb/template_files/project/requirements.txt:
--------------------------------------------------------------------------------
1 | uliweb
2 | plugs
--------------------------------------------------------------------------------
/uliweb/template_files/project/wsgi_handler.py:
--------------------------------------------------------------------------------
1 | import sys, os
2 |
3 | path = os.path.dirname(os.path.abspath(__file__))
4 | if path not in sys.path:
5 | sys.path.insert(0, path)
6 |
7 | from uliweb.manage import make_simple_application
8 | application = make_simple_application(project_dir=path)
9 |
--------------------------------------------------------------------------------
/uliweb/template_files/support/gevent-socketio/gevent_socketio_handler.py:
--------------------------------------------------------------------------------
1 | import sys, os
2 | import getopt
3 | from gevent import monkey
4 | from socketio.server import SocketIOServer
5 |
6 | monkey.patch_all()
7 |
8 | hostname = '127.0.0.1'
9 | port = 80
10 |
11 | opts, args = getopt.getopt(sys.argv[1:], "h:p:", [])
12 | for o, a in opts:
13 | if o == '-h':
14 | hostname = a
15 | elif o == '-p':
16 | port = int(a)
17 |
18 | path = os.path.dirname(os.path.abspath(__file__))
19 | if path not in sys.path:
20 | sys.path.insert(0, path)
21 |
22 | from uliweb.manage import make_simple_application
23 | application = make_simple_application(project_dir=path)
24 |
25 | SocketIOServer((hostname, port), application, resource="socket.io").serve_forever()
26 |
--------------------------------------------------------------------------------
/uliweb/template_files/support/gevent/gevent_handler.py:
--------------------------------------------------------------------------------
1 | import sys, os
2 | import getopt
3 | from gevent.wsgi import WSGIServer
4 | from gevent import monkey
5 |
6 | monkey.patch_all()
7 |
8 | hostname = '127.0.0.1'
9 | port = 80
10 |
11 | opts, args = getopt.getopt(sys.argv[1:], "h:p:", [])
12 | for o, a in opts:
13 | if o == '-h':
14 | hostname = a
15 | elif o == '-p':
16 | port = int(a)
17 |
18 | path = os.path.dirname(os.path.abspath(__file__))
19 | if path not in sys.path:
20 | sys.path.insert(0, path)
21 |
22 | from uliweb.manage import make_simple_application
23 | application = make_simple_application(project_dir=path)
24 |
25 | http_server = WSGIServer((hostname, port), application)
26 | http_server.serve_forever()
27 |
28 |
--------------------------------------------------------------------------------
/uliweb/template_files/support/tornado/tornado_handler.py:
--------------------------------------------------------------------------------
1 | import sys, os
2 | import getopt
3 | import tornado.wsgi
4 | import tornado.httpserver
5 | import tornado.ioloop
6 |
7 | hostname = '127.0.0.1'
8 | port = 80
9 |
10 | opts, args = getopt.getopt(sys.argv[1:], "h:p:", [])
11 | for o, a in opts:
12 | if o == '-h':
13 | hostname = a
14 | elif o == '-p':
15 | port = int(a)
16 |
17 | path = os.path.dirname(os.path.abspath(__file__))
18 | if path not in sys.path:
19 | sys.path.insert(0, path)
20 |
21 | from uliweb.manage import make_simple_application
22 | application = make_simple_application(project_dir=path)
23 |
24 | container = tornado.wsgi.WSGIContainer(application)
25 | http_server = tornado.httpserver.HTTPServer(container, xheaders=True)
26 | http_server.listen(port, address=hostname)
27 | tornado.ioloop.IOLoop.instance().start()
28 |
29 |
--------------------------------------------------------------------------------
/uliweb/utils/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/limodou/uliweb/8bc827fa6bf7bf58aa8136b6c920fe2650c52422/uliweb/utils/__init__.py
--------------------------------------------------------------------------------
/uliweb/utils/ipython_extension.py:
--------------------------------------------------------------------------------
1 | def make_shell_env(**kwargs):
2 | import os
3 | import sys
4 | from uliweb import functions, settings
5 | from uliweb.core.SimpleFrame import Dispatcher
6 | from uliweb.manage import make_simple_application
7 |
8 | project_dir = '.'
9 | application = make_simple_application(project_dir=project_dir)
10 |
11 | if project_dir not in sys.path:
12 | sys.path.insert(0, project_dir)
13 |
14 | app = application
15 | while app:
16 | if isinstance(app, Dispatcher):
17 | break
18 | else:
19 | app = app.app
20 |
21 | env = {'application':app, 'settings':settings, 'functions':functions}
22 | return env
23 |
24 | def patch_ipython():
25 | from IPython.lib import pretty
26 | import IPython.core.formatters as formatters
27 |
28 | def _safe_get_formatter_method(obj, name):
29 | """Safely get a formatter method
30 |
31 | Enable classes formatter method
32 | """
33 | method = pretty._safe_getattr(obj, name, None)
34 | if callable(method):
35 | # obj claims to have repr method...
36 | if callable(pretty._safe_getattr(obj, '_ipython_canary_method_should_not_exist_', None)):
37 | # ...but don't trust proxy objects that claim to have everything
38 | return None
39 | return method
40 | formatters._safe_get_formatter_method = _safe_get_formatter_method
41 |
--------------------------------------------------------------------------------
/uliweb/utils/rst.py:
--------------------------------------------------------------------------------
1 | from docutils.core import publish_parts
2 | from docutils import nodes
3 | from docutils.parsers.rst import directives
4 | import re
5 | import threading
6 |
7 | g_data = threading.local()
8 | g_data.g_style = {}
9 |
10 | class highlight_block(nodes.General, nodes.Text):pass
11 |
12 | from docutils.writers.html4css1 import Writer, HTMLTranslator
13 |
14 | class SimpleWrite(Writer):
15 | def __init__(self):
16 | Writer.__init__(self)
17 | self.translator_class = SimpleHTMLTranslator
18 |
19 | class SimpleHTMLTranslator(HTMLTranslator):
20 | def visit_highlight_block(self, node):
21 | self.body.append(node.astext())
22 |
23 | def depart_highlight_block(self, node):
24 | pass
25 |
26 | def r_space(m):
27 | return len(m.group()) * ' '
28 |
29 | re_space = re.compile(r'^[ ]+', re.MULTILINE)
30 | def code(name, arguments, options, content, lineno,
31 | content_offset, block_text, state, state_machine):
32 | global g_data
33 |
34 | if len(arguments) > 0:
35 | lang = arguments[0]
36 | else:
37 | lang = ''
38 | style, text = highlight('\n'.join(content), lang)
39 | text = re_space.sub(r_space, text)
40 | g_data.g_style[lang] = style
41 | return [highlight_block(text)]
42 |
43 | code.content = 1
44 | code.arguments = (0, 1, 1)
45 | directives.register_directive('code', code)
46 |
47 | def to_html(text, level=1, part='html_body'):
48 | global g_data
49 | g_data.g_style = {}
50 | source = text
51 | parts = publish_parts(source, writer=SimpleWrite(), settings_overrides={'initial_header_level':level})
52 | if g_data.g_style:
53 | style = ''
54 | else:
55 | style = ''
56 | return style + '\n' + parts[part]
57 |
58 | def parts(text, level=1, part='html_body'):
59 | global g_data
60 | g_data.g_style = {}
61 | source = text
62 | parts = publish_parts(source, writer=SimpleWrite(), settings_overrides={'initial_header_level':level})
63 | if g_data.g_style:
64 | style = ''
65 | else:
66 | style = ''
67 | return style + '\n' + parts[part], parts
68 |
69 | def highlight(code, lang):
70 | from pygments import highlight
71 | from pygments.lexers import get_lexer_by_name, guess_lexer, PythonLexer
72 | from pygments.formatters import HtmlFormatter
73 | try:
74 | lexer = get_lexer_by_name(lang)
75 | except:
76 | try:
77 | lexer = guess_lexer(code)
78 | lang = lexer.aliases[0]
79 | except:
80 | lexer = PythonLexer()
81 | lang = 'python'
82 | lang = lang.replace('+', '_')
83 | return HtmlFormatter().get_style_defs('.highlight_'+lang), highlight(code, lexer, HtmlFormatter(cssclass='highlight_'+lang))
--------------------------------------------------------------------------------
/uliweb/utils/storage.py:
--------------------------------------------------------------------------------
1 | """
2 | This file is part of web2py Web Framework (Copyrighted, 2007)
3 | Developed by Massimo Di Pierro
4 | License: GPL v2
5 | """
6 |
7 | class Storage(dict):
8 | """
9 | A Storage object is like a dictionary except `obj.foo` can be used
10 | in addition to `obj['foo']`.
11 |
12 | >>> o = Storage(a=1)
13 | >>> o.a
14 | 1
15 | >>> o['a']
16 | 1
17 | >>> o.a = 2
18 | >>> o['a']
19 | 2
20 | >>> del o.a
21 | >>> o.a
22 | None
23 |
24 | """
25 | def __getattr__(self, key):
26 | try: return self[key]
27 | except KeyError, k: return None
28 | def __setattr__(self, key, value):
29 | self[key] = value
30 | def __delattr__(self, key):
31 | try: del self[key]
32 | except KeyError, k: raise AttributeError, k
33 | def __repr__(self):
34 | return ''
35 | def __getstate__(self):
36 | return dict(self)
37 | def __setstate__(self,value):
38 | for k,v in value.items(): self[k]=v
39 |
--------------------------------------------------------------------------------
/uliweb/utils/textconvert.py:
--------------------------------------------------------------------------------
1 | #coding=utf-8
2 | import re
3 | import cgi
4 |
5 | re_string_html = re.compile(r'(?P[<&>])|(?P^[ \t]+)|(?P\r\n|\r|\n)|(?P(^|\s*)(http|ftp|https)://[\w\-\.,@?^=%&:/~\+#]+)', re.S|re.M|re.I)
6 | re_string = re.compile(r'(?P[<&>])|(?P^[ \t]+)|(?P\r\n|\r|\n)', re.S|re.M|re.I)
7 | def text2html(text, tabstop=4, link=True):
8 | if not text:
9 | return ''
10 | def do_sub(m):
11 | c = m.groupdict()
12 | if c['htmlchars']:
13 | return cgi.escape(c['htmlchars'])
14 | if c['lineend']:
15 | return '
'
16 | elif c['space']:
17 | t = m.group().replace('\t', ' '*tabstop)
18 | t = t.replace(' ', ' ')
19 | return t
20 | else:
21 | url = m.group('protocal')
22 | if url.startswith(' '):
23 | prefix = ' '
24 | url = url[1:]
25 | else:
26 | prefix = ''
27 | return '%s%s' % (prefix, url, url)
28 | if link:
29 | return re.sub(re_string_html, do_sub, text)
30 | else:
31 | return re.sub(re_string, do_sub, text)
32 |
33 | if __name__ == '__main__':
34 | text=("I like python!\r\n"
35 | "UliPad <>: http://code.google.com/p/ulipad/\r\n"
36 | "UliWeb <>: http://uliwebproject.appspot.com\r\n"
37 | "My Blog: http://hi.baidu.com/limodou")
38 | print text2html(text)
39 |
--------------------------------------------------------------------------------
/uliweb/utils/timeit.py:
--------------------------------------------------------------------------------
1 | import time
2 | from contextlib import contextmanager
3 |
4 | @contextmanager
5 | def timeit(output):
6 | """
7 | If output is string, then print the string and also time used
8 | """
9 | b = time.time()
10 | yield
11 | print output, 'time used: %.3fs' % (time.time()-b)
--------------------------------------------------------------------------------
/uliweb/utils/timesince.py:
--------------------------------------------------------------------------------
1 | import datetime
2 | import uliweb.utils.date as date
3 | from uliweb.i18n import ungettext, ugettext
4 |
5 | def timesince(d, now=None, pos=True, flag=False):
6 | """
7 | pos means calculate which direction, pos = True, now - d, pos = False, d - now
8 | flag means return value type, True will return since, message and Flase return message
9 | >>> d = datetime.datetime(2009, 10, 1, 12, 23, 19)
10 | >>> timesince(d, d, True)
11 | >>> now = datetime.datetime(2009, 10, 1, 12, 24, 19)
12 | >>> timesince(d, now, True)
13 | u'1 minute ago'
14 | >>> now = datetime.datetime(2009, 10, 1, 12, 24, 30)
15 | >>> timesince(d, now, True)
16 | u'1 minute ago'
17 | >>> now = datetime.datetime(2009, 9, 28, 12, 24, 30)
18 | >>> timesince(d, now, True)
19 | u'2 days, 23 hours later'
20 | >>> now = datetime.datetime(2009, 10, 3, 12, 24, 30)
21 | >>> timesince(d, now, True)
22 | u'2 days ago'
23 | """
24 | if not d:
25 | if flag:
26 | return 0, ''
27 | else:
28 | return ''
29 | chunks = (
30 | (60 * 60 * 24 * 365, lambda n: ungettext('year', 'years', n)),
31 | (60 * 60 * 24 * 30, lambda n: ungettext('month', 'months', n)),
32 | (60 * 60 * 24 * 7, lambda n : ungettext('week', 'weeks', n)),
33 | (60 * 60 * 24, lambda n : ungettext('day', 'days', n)),
34 | (60 * 60, lambda n: ungettext('hour', 'hours', n)),
35 | (60, lambda n: ungettext('minute', 'minutes', n))
36 | )
37 |
38 | if not now:
39 | now = date.now()
40 | else:
41 | now = date.to_datetime(now)
42 | d = date.to_datetime(d)
43 |
44 | delta = now - (d - datetime.timedelta(0, 0, d.microsecond))
45 | oldsince = since = delta.days * 24 * 60 * 60 + delta.seconds
46 |
47 | suffix = ''
48 | if pos:
49 | if since >= 0:
50 | suffix = ugettext(' ago')
51 | elif since < 0:
52 | suffix = ugettext(' later')
53 | since *= -1
54 |
55 | for i, (seconds, name) in enumerate(chunks):
56 | count = since // seconds
57 | if count != 0:
58 | break
59 | s = ('%(number)d %(type)s') % {'number': count, 'type': name(count)}
60 | if i + 1 < len(chunks):
61 | # Now get the second item
62 | seconds2, name2 = chunks[i + 1]
63 | count2 = (since - (seconds * count)) // seconds2
64 | if count2 != 0:
65 | s += (', %(number)d %(type)s') % {'number': count2, 'type': name2(count2)}
66 | #if flag==True, then return twe elements (since, message)
67 | if flag:
68 | return oldsince, s + suffix
69 | else:
70 | return s + suffix
71 |
--------------------------------------------------------------------------------
/uliweb/utils/whocallme.py:
--------------------------------------------------------------------------------
1 | def who_called_me(show_filename=True, out=None, indent=' '):
2 | def _wrapper(fn):
3 | def _inner_wrapper(*args, **kwargs):
4 | import sys
5 | import inspect
6 | output = out or sys.stdout
7 | assert hasattr(output, 'write'), \
8 | 'argument \'out\' of function \'who_called_me\' must have a write method'
9 | index = 0
10 | stack = inspect.stack()
11 | stack.reverse()
12 | # remove ourself from the stack list
13 | stack.pop()
14 | for record in stack:
15 | frame = record[0]
16 | line = frame.f_lineno
17 | func_name = frame.f_code.co_name
18 | if show_filename:
19 | descr = frame.f_code.co_filename
20 | else:
21 | descr = frame.f_globals["__name__"]
22 | print >>output, '%sFile "%s", line %d, in %s' % (indent*index, descr, line, func_name)
23 | # print >>output, '%s%s@%s:%d' % (indent*index, descr, func_name, line)
24 | # to be safe explicitly delete the stack frame reference
25 | # @see http://docs.python.org/lib/inspect-stack.html
26 | del frame
27 | index += 1
28 | del stack
29 | if hasattr(output, 'flush'):
30 | output.flush()
31 | return fn(*args, **kwargs)
32 | return _inner_wrapper
33 | return _wrapper
34 |
35 | def print_frame(out=None, depth=1):
36 | import sys
37 | import inspect
38 |
39 | # remove ourself from the stack list
40 | output = out or sys.stdout
41 | assert hasattr(output, 'write'), \
42 | 'argument \'out\' of function \'who_called_me\' must have a write method'
43 | index = 0
44 | indent = ' '
45 | stack = inspect.stack()
46 | stack.reverse()
47 | stack.pop()
48 | for record in stack[-1*depth-1:-1]:
49 | if index >= depth:
50 | break
51 | frame = record[0]
52 | line = frame.f_lineno
53 | func_name = frame.f_code.co_name
54 | descr = frame.f_code.co_filename
55 | output.write('%sFile "%s", line %d, in %s' % (indent * index, descr, line, func_name))
56 | # print >>output, '%s%s@%s:%d' % (indent*index, descr, func_name, line)
57 | # to be safe explicitly delete the stack frame reference
58 | # @see http://docs.python.org/lib/inspect-stack.html
59 | del frame
60 | index += 1
61 | if hasattr(output, 'flush'):
62 | output.flush()
63 |
--------------------------------------------------------------------------------
/uliweb/wsgi/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/limodou/uliweb/8bc827fa6bf7bf58aa8136b6c920fe2650c52422/uliweb/wsgi/__init__.py
--------------------------------------------------------------------------------
/uliweb/wsgi/profile.py:
--------------------------------------------------------------------------------
1 | import os, sys
2 | import hotshot
3 | import hotshot.stats
4 | from cStringIO import StringIO
5 |
6 | PROFILE_DATA_DIR = "./profile"
7 | class ProfileApplication(object):
8 | def __init__(self, app):
9 | self.path = path = PROFILE_DATA_DIR
10 | if not os.path.exists(path):
11 | os.makedirs(path)
12 | os.chmod(path, 0755)
13 | self.app = app
14 |
15 | def __call__(self, environ, start_response):
16 | profname = "%s.prof" % (environ['PATH_INFO'].strip("/").replace('/', '.'))
17 | profname = os.path.join(self.path, profname)
18 | prof = hotshot.Profile(profname)
19 | # prof.start()
20 | ret = prof.runcall(self.app, environ, start_response)
21 | prof.close()
22 |
23 | out = StringIO()
24 | old_stdout = sys.stdout
25 | sys.stdout = out
26 |
27 | stats = hotshot.stats.load(profname)
28 | #stats.strip_dirs()
29 | stats.sort_stats('time', 'calls')
30 | stats.print_stats()
31 |
32 | sys.stdout = old_stdout
33 | stats_str = out.getvalue()
34 |
35 | from uliweb.utils.textconvert import text2html
36 | text = text2html(stats_str)
37 | outputfile = profname + '.html'
38 | file(outputfile, 'wb').write(text)
39 |
40 | return ret
41 |
42 |
--------------------------------------------------------------------------------