python - 如何通过 mod-wsgi 使用 FCKEditor 的图像上传和浏览器?

标签 python django fckeditor mod-wsgi

我在 Apache/mod-wsgi 提供的 Django 应用程序中使用 FCKEditor。我不想只为FCKEditor安装php,而且我看到FCKEditor通过Python提供图像上传和图像浏览。我只是还没有找到关于如何设置这一切的良好说明。

目前 Django 正在使用此设置通过 wsgi 接口(interface)运行:

import os, sys

DIRNAME = os.sep.join(os.path.abspath(__file__).split(os.sep)[:-3])
sys.path.append(DIRNAME)
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

在fckeditor中的编辑器->文件管理器->连接器->py目录中有一个名为wsgi.py的文件:

from connector import FCKeditorConnector
from upload import FCKeditorQuickUpload

import cgitb
from cStringIO import StringIO

# Running from WSGI capable server (recomended)
def App(environ, start_response):
    "WSGI entry point. Run the connector"
    if environ['SCRIPT_NAME'].endswith("connector.py"):
        conn = FCKeditorConnector(environ)
    elif environ['SCRIPT_NAME'].endswith("upload.py"):
        conn = FCKeditorQuickUpload(environ)
    else:
        start_response ("200 Ok", [('Content-Type','text/html')])
        yield "Unknown page requested: "
        yield environ['SCRIPT_NAME']
        return
    try:
        # run the connector
        data = conn.doResponse()
        # Start WSGI response:
        start_response ("200 Ok", conn.headers)
        # Send response text
        yield data
    except:
        start_response("500 Internal Server Error",[("Content-type","text/html")])
        file = StringIO()
        cgitb.Hook(file = file).handle()
    yield file.getvalue()

我需要这两件事一起工作,通过修改我的 django wsgi 文件来正确服务 fckeditor 部分,或者让 apache 在单个域上正确服务 django 和 fckeditor。

最佳答案

介绍如何嵌入FCK编辑器并实现图片上传。

首先你需要编辑fckconfig.js来更改图片上传 URL 指向服务器内的某个 URL。

FCKConfig.ImageUploadURL = "/myapp/root/imageUploader";

这将指向服务器相对 URL 以接收上传。 FCK 将使用 CGI 变量将上传的文件发送到该处理程序 使用 multipart/form-data 编码的名称“NewFile”。不幸的是你 必须实现/myapp/root/imageUploader,因为我不认为 FCK 发行版的东西可以很容易地适应其他框架。

imageUploader 应该提取 NewFile 并存储它 服务器上的某个地方。 /myapp/root/imageUploader 生成的响应应该模拟 /editor/.../fckoutput.py 中构造的 HTML。 像这样的东西(whiff模板格式)

{{env
    whiff.content_type: "text/html",
    whiff.headers: [
        ["Expires","Mon, 26 Jul 1997 05:00:00 GMT"],
        ["Cache-Control","no-store, no-cache, must-revalidate"],
        ["Cache-Control","post-check=0, pre-check=0"],
        ["Pragma","no-cache"]
        ]
/}}

<script>
//alert("!! RESPONSE RECIEVED");
errorNumber = 0;
fileUrl = "fileurl.png";
fileName = "filename.png";
customMsg = "";
window.parent.OnUploadCompleted(errorNumber, fileUrl, fileName, customMsg);
</script>

顶部的 {{env ...}} 内容指示内容类型和 建议发送的 HTTP header 。 fileUrl 应该是 URL 用于在服务器上查找图像。

以下是获取 html 片段的基本步骤 生成 FCK 编辑器小部件。唯一棘手的部分是你必须把 在 os.environ 中正确识别客户端——这很丑陋 但这就是 FCK 库现在的工作方式(我提交了一个错误 报告)。

import fckeditor # you must have the fck editor python support installed to use this module
import os

inputName = "myInputName" # the name to use for the input element in the form
basePath = "/server/relative/path/to/fck/installation/" # the location of FCK static files
if basePath[-1:]!="/":
        basePath+="/" # basepath must end in slash
oFCKeditor = fckeditor.FCKeditor(inputName)
oFCKeditor.BasePath = basePath
oFCKeditor.Height = 300 # the height in pixels of the editor
oFCKeditor.Value = "<h1>initial html to be editted</h1>"
os.environ["HTTP_USER_AGENT"] = "Mozilla/5.0 (Macintosh; U;..." # or whatever
# there must be some way to figure out the user agent in Django right?
htmlOut = oFCKeditor.Create()
# insert htmlOut into your page where you want the editor to appear
return htmlOut

上面的内容未经测试,但它基于下面经过测试的内容。

以下是如何使用 mod-wsgi 使用 FCK 编辑器: 从技术上讲,它使用了 WHIFF 的几个功能(请参阅 WHIFF.sourceforge.net ), -- 事实上它是 WHIFF 发行版的一部分 -- 但 WHIFF 功能很容易被删除。

我不知道如何在 Django 中安装它,但是如果 Django 允许轻松安装 wsgi 应用程序,您 应该可以做到。

注意:FCK 允许客户端注入(inject)几乎任何东西 进入 HTML 页面——您将需要过滤返回值以防止邪恶 攻击。 (例如:参见whiff.middleware.TestSafeHTML中间件 如何执行此操作的示例)。

    
"""
Introduce an FCK editor input element. (requires FCKeditor http://www.fckeditor.net/).

Note: this implementation can generate values containing code injection attacks if you
  don't filter the output generated for evil tags and values.
"""

import fckeditor # you must have the fck editor python support installed to use this module
from whiff.middleware import misc
import os

class FCKInput(misc.utility):
    def __init__(self,
                 inputName, # name for input element
                 basePath, # server relative URL root for FCK HTTP install
                 value = ""):  # initial value for input
        self.inputName = inputName
        self.basePath = basePath
        self.value = value
    def __call__(self, env, start_response):
        inputName = self.param_value(self.inputName, env).strip()
        basePath = self.param_value(self.basePath, env).strip()
        if basePath[-1:]!="/":
            basePath+="/"
        value = self.param_value(self.value, env)
        oFCKeditor = fckeditor.FCKeditor(inputName)
        oFCKeditor.BasePath = basePath
        oFCKeditor.Height = 300 # this should be a require!
        oFCKeditor.Value = value
        # hack around a bug in fck python library: need to put the user agent in os.environ
        # XXX this hack is not safe for multi threaded servers (theoretically)... need to lock on os.env
        os_environ = os.environ
        new_os_env = os_environ.copy()
        new_os_env.update(env)
        try:
            os.environ = new_os_env
            htmlOut = oFCKeditor.Create()
        finally:
            # restore the old os.environ
            os.environ = os_environ
        start_response("200 OK", [('Content-Type', 'text/html')])
        return [htmlOut]

__middleware__ = FCKInput

def test():
    env = {
        "HTTP_USER_AGENT":
        "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14"
        }
    f = FCKInput("INPUTNAME", "/MY/BASE/PATH", "THE HTML VALUE TO START WITH")
    r = f(env, misc.ignore)
    print "test result"
    print "".join(list(r))

if __name__=="__main__":
    test()

请参阅此工作,例如, http://aaron.oirt.rutgers.edu/myapp/docs/W1500.whyIsWhiffCool .

顺便说一句:谢谢。无论如何,我需要调查一下这个问题。

关于python - 如何通过 mod-wsgi 使用 FCKEditor 的图像上传和浏览器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/803613/

相关文章:

asp.net - 服务器未发回正确的 XML 响应

FCKEditor 在 IE10 中不起作用

javascript - Vim - 语法突出显示 - Javascript - 字符串和 bool 值相同的颜色

python - 如何使用 PIL 裁剪图像?

python - 如何按列提取pd行,并向左移动2列

while循环中的Python套接字接收数据不会停止

python - DRF : Validate nested serializer data when creating, 但更新时没有

python - Django,保存模型窗体

django - 对包含多个提交按钮的 Django 表单进行单元测试

html - FCKeditor 对比 TinyMCE 和 XHTML 合规性