Skip to content

Commit

Permalink
2.14@休假
Browse files Browse the repository at this point in the history
  • Loading branch information
Madridspark committed Feb 14, 2017
1 parent 62571a2 commit 6bca9d9
Show file tree
Hide file tree
Showing 366 changed files with 133,592 additions and 72 deletions.
100 changes: 100 additions & 0 deletions .vscode/.ropeproject/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# The default ``config.py``
# flake8: noqa


def set_prefs(prefs):
"""This function is called before opening the project"""

# Specify which files and folders to ignore in the project.
# Changes to ignored resources are not added to the history and
# VCSs. Also they are not returned in `Project.get_files()`.
# Note that ``?`` and ``*`` match all characters but slashes.
# '*.pyc': matches 'test.pyc' and 'pkg/test.pyc'
# 'mod*.pyc': matches 'test/mod1.pyc' but not 'mod/1.pyc'
# '.svn': matches 'pkg/.svn' and all of its children
# 'build/*.o': matches 'build/lib.o' but not 'build/sub/lib.o'
# 'build//*.o': matches 'build/lib.o' and 'build/sub/lib.o'
prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject',
'.hg', '.svn', '_svn', '.git', '.tox']

# Specifies which files should be considered python files. It is
# useful when you have scripts inside your project. Only files
# ending with ``.py`` are considered to be python files by
# default.
#prefs['python_files'] = ['*.py']

# Custom source folders: By default rope searches the project
# for finding source folders (folders that should be searched
# for finding modules). You can add paths to that list. Note
# that rope guesses project source folders correctly most of the
# time; use this if you have any problems.
# The folders should be relative to project root and use '/' for
# separating folders regardless of the platform rope is running on.
# 'src/my_source_folder' for instance.
#prefs.add('source_folders', 'src')

# You can extend python path for looking up modules
#prefs.add('python_path', '~/python/')

# Should rope save object information or not.
prefs['save_objectdb'] = True
prefs['compress_objectdb'] = False

# If `True`, rope analyzes each module when it is being saved.
prefs['automatic_soa'] = True
# The depth of calls to follow in static object analysis
prefs['soa_followed_calls'] = 0

# If `False` when running modules or unit tests "dynamic object
# analysis" is turned off. This makes them much faster.
prefs['perform_doa'] = True

# Rope can check the validity of its object DB when running.
prefs['validate_objectdb'] = True

# How many undos to hold?
prefs['max_history_items'] = 32

# Shows whether to save history across sessions.
prefs['save_history'] = True
prefs['compress_history'] = False

# Set the number spaces used for indenting. According to
# :PEP:`8`, it is best to use 4 spaces. Since most of rope's
# unit-tests use 4 spaces it is more reliable, too.
prefs['indent_size'] = 4

# Builtin and c-extension modules that are allowed to be imported
# and inspected by rope.
prefs['extension_modules'] = []

# Add all standard c-extensions to extension_modules list.
prefs['import_dynload_stdmods'] = True

# If `True` modules with syntax errors are considered to be empty.
# The default value is `False`; When `False` syntax errors raise
# `rope.base.exceptions.ModuleSyntaxError` exception.
prefs['ignore_syntax_errors'] = False

# If `True`, rope ignores unresolvable imports. Otherwise, they
# appear in the importing namespace.
prefs['ignore_bad_imports'] = False

# If `True`, rope will insert new module imports as
# `from <package> import <module>` by default.
prefs['prefer_module_from_imports'] = False

# If `True`, rope will transform a comma list of imports into
# multiple separate import statements when organizing
# imports.
prefs['split_imports'] = False

# If `True`, rope will sort imports alphabetically by module name
# instead of alphabetically by import statement, with from imports
# after normal imports.
prefs['sort_imports_alphabetically'] = False


def project_opened(project):
"""This function is called after opening the project"""
# Do whatever you like here!
Binary file added .vscode/.ropeproject/objectdb
Binary file not shown.
Empty file added DjangoUeditor/__init__.py
Empty file.
Binary file added DjangoUeditor/__init__.pyc
Binary file not shown.
34 changes: 34 additions & 0 deletions DjangoUeditor/adminx.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#coding:utf-8
#__author__ = 'sai'
#DjangoUeditor Xadmin plugin

import xadmin
from django.db.models import TextField
from xadmin.views import BaseAdminPlugin, ModelFormAdminView, DetailAdminView
from DjangoUeditor.models import UEditorField
from DjangoUeditor.widgets import UEditorWidget
from django.conf import settings

class XadminUEditorWidget(UEditorWidget):
def __init__(self,**kwargs):
self.ueditor_settings=kwargs
self.Media.js = None
super(XadminUEditorWidget, self).__init__(kwargs)

class UeditorPlugin(BaseAdminPlugin):

def get_field_style(self, attrs, db_field, style, **kwargs):
if style == 'ueditor':
if isinstance(db_field, UEditorField):
return {'widget': XadminUEditorWidget(**db_field.formfield().widget.attrs)}
if isinstance(db_field, TextField):
return {'widget': XadminUEditorWidget}
return attrs

def block_extrahead(self, context, nodes):
js = '<script type="text/javascript" src="%s"></script>' % (settings.STATIC_URL + "ueditor/ueditor.config.js")
js += '<script type="text/javascript" src="%s"></script>' % (settings.STATIC_URL + "ueditor/ueditor.all.min.js")
nodes.append(js)

xadmin.site.register_plugin(UeditorPlugin, DetailAdminView)
xadmin.site.register_plugin(UeditorPlugin, ModelFormAdminView)
193 changes: 193 additions & 0 deletions DjangoUeditor/commands.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
# -*- coding: utf-8 -*-
from . import settings as USettings
from django.utils.six.moves.urllib.parse import urljoin


class UEditorEventHandler(object):
"""用来处理UEditor的事件侦听"""

def on_selectionchange(self):
return ""

def on_contentchange(self):
return ""

def render(self, editorID):
jscode = """
%(editor)s.addListener('%(event)s', function () {
%(event_code)s
});"""
event_codes = []
# 列出所有on_打头的方法,然后在ueditor中进行侦听
events = filter(lambda x: x[0:3] == "on_", dir(self))
for event in events:
try:
event_code = getattr(self, event)()
if event_code:
event_code = event_code % {"editor": editorID}
event_codes.append(jscode % {"editor": editorID, "event": event[
3:], "event_code": event_code})
except:
pass

if len(event_codes) == 0:
return ""
else:
return "\n".join(event_codes)


class UEditorCommand(object):
"""
为前端增加按钮,下拉等扩展,
"""

def __init__(self, **kwargs):
self.uiName = kwargs.pop("uiName", "")
self.index = kwargs.pop("index", 0)
self.title = kwargs.pop("title", self.uiName)
self.ajax_url = kwargs.pop("ajax_url", "")

def render_ui(self, editor):
"""" 创建ueditor的ui扩展对象的js代码,如button,combo等 """
raise NotImplementedError

def render_ajax_command(self):
""""生成通过ajax调用后端命令的前端ajax代码"""
if not self.ajax_url:
return ""

return u"""
UE.ajax.request( '%(ajax_url)s', {
data: {
name: 'ueditor'
},
onsuccess: function ( xhr ) {%(ajax_success)s},
onerror: function ( xhr ){ %(ajax_error)s }
});
""" % {
"ajax_url": self.ajax_url,
"ajax_success": self.onExecuteAjaxCommand("success"),
"ajax_error": self.onExecuteAjaxCommand("error")
}

def render_command(self):
"""" 返回注册命令的js定义 """
cmd = self.onExecuteCommand()
ajax_cmd = self.render_ajax_command()
queryvalue_command = self.onExecuteQueryvalueCommand()
cmds = []
if cmd or ajax_cmd:
cmds.append( u"""execCommand: function() {
%(exec_cmd)s
%(exec_ajax_cmd)s
}
""" % {"exec_cmd": cmd, "exec_ajax_cmd": ajax_cmd},)

if queryvalue_command:
cmds.append(u"""queryCommandValue:function(){
%s
}""" % queryvalue_command)
if len(cmds) > 0:
return u"""
editor.registerCommand(uiName, {
%s
});
""" % ",".join(cmds)
else:
return ""

def render(self, editorID):
return u"""
UE.registerUI("%(uiName)s", function(editor, uiName) {
%(registerCommand)s
%(uiObject)s
},%(index)s,"%(editor)s");
""" % {
"registerCommand": self.render_command(),
"uiName": self.uiName,
"uiObject": self.render_ui(editorID),
"index": self.index,
"editor": editorID
}

def onExecuteCommand(self):
""" 返回执行Command时的js代码 """
return ""

def onExecuteAjaxCommand(self, state):
""" 返回执行Command时发起Ajax调用成功与失败的js代码 """
return ""

def onExecuteQueryvalueCommand(self):
"""" 返回执行QueryvalueCommand时的js代码 """
return ""


class UEditorButtonCommand(UEditorCommand):

def __init__(self, **kwargs):
self.icon = kwargs.pop("icon", "")
super(UEditorButtonCommand, self).__init__(**kwargs)

def onClick(self):
""""按钮单击js代码,默认执行uiName命令,默认会调用Command """
return """
editor.execCommand(uiName);
"""

def render_ui(self, editorID):
""" 创建button的js代码: """
return """
var btn = new UE.ui.Button({
name: uiName,
title: "%(title)s",
cssRules: "background-image:url('%(icon)s')!important;",
onclick: function() {
%(onclick)s
}
});
return btn
""" % {
"icon": urljoin(USettings.gSettings.MEDIA_URL, self.icon),
"onclick": self.onClick(),
"title": self.title
}


class UEditorComboCommand(UEditorCommand):

def __init__(self, **kwargs):
self.items = kwargs.pop("items", [])
self.initValue = kwargs.pop("initValue", "")

super(UEditorComboCommand, self).__init__(**kwargs)

def get_items(self):
return self.items

def onSelect(self):
return ""

def render_ui(self, editorID):
""" 创建combo的js代码: """
return """
var combox = new UE.ui.Combox({
editor:editor,
items:%(items)s,
onselect:function (t, index) {
%(onselect)s
},
title:'%(title)s',
initValue:'%(initValue)s'
});
return combox;
""" % {
"title": self.title,
"items": str(self.get_items()),
"onselect": self.onSelect(),
"initValue": self.initValue
}


class UEditorDialogCommand(UEditorCommand):
pass
Binary file added DjangoUeditor/commands.pyc
Binary file not shown.
42 changes: 42 additions & 0 deletions DjangoUeditor/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# -*- coding: utf-8 -*-
from django import forms
from widgets import UEditorWidget
from DjangoUeditor.models import UEditorField as ModelUEditorField


class UEditorField(forms.CharField):
def __init__(self, label, width=600, height=300, toolbars="full",
imagePath="", filePath="", upload_settings={},
settings={}, command=None, event_handler=None, *args,
**kwargs):
uSettings = locals().copy()
del uSettings["self"], uSettings[
"label"], uSettings["args"], uSettings["kwargs"]
kwargs["widget"] = UEditorWidget(attrs=uSettings)
kwargs["label"] = label
super(UEditorField, self).__init__(*args, **kwargs)


def UpdateUploadPath(model_form, model_inst=None):
""" 遍历model字段,如果是UEditorField则需要重新计算路径 """
if model_inst is not None:
try:
for field in model_inst._meta.fields:
if isinstance(field, ModelUEditorField):
model_form.__getitem__(
field.name).field.widget.recalc_path(model_inst)
except:
pass


class UEditorModelForm(forms.ModelForm):

def __init__(self, *args, **kwargs):
super(UEditorModelForm, self).__init__(*args, **kwargs)
try:
if 'instance' in kwargs:
UpdateUploadPath(self, kwargs["instance"])
else:
UpdateUploadPath(self, None)
except Exception:
pass
Loading

0 comments on commit 6bca9d9

Please sign in to comment.