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

时间:2009-04-29 18:23:30

标签: python django fckeditor mod-wsgi

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

所以目前Django使用这个设置运行wsgi接口:

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()

在编辑器> filemanager->连接器 - > py目录中的fckeditor中有一个名为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服务,这两个方面有两个一起工作。

2 个答案:

答案 0 :(得分:1)

介绍如何嵌入FCK编辑器并启用图像上传。

首先,您需要编辑fckconfig.js以更改图像上传 指向服务器内部某个URL的URL。

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

这将指向用于接收上载的服务器相对URL。 FCK将使用CGI变量将上载的文件发送到该处理程序 名称“NewFile”使用multipart / form-data编码。不幸的是你 将不得不实现/ 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标头。 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允许客户端注入几乎任何东西 进入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

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

答案 1 :(得分:0)

编辑:最后我对这个解决方案也不满意所以我做了Django app来处理文件上传和浏览。

这是我在阅读fckeditor代码后最终共同攻击的解决方案:

import os, sys

def fck_handler(environ, start_response):
    path = environ['PATH_INFO']
    if path.endswith(('upload.py', 'connector.py')):
        sys.path.append('/#correct_path_to#/fckeditor/editor/filemanager/connectors/py/')
        if path.endswith('upload.py'):
            from upload import FCKeditorQuickUpload
            conn = FCKeditorQuickUpload(environ)
        else:
            from connector import FCKeditorConnector
            conn = FCKeditorConnector(environ)
        try:
            data = conn.doResponse()
            start_response('200 Ok', conn.headers)
            return data
        except:
            start_response("500 Internal Server Error",[("Content-type","text/html")])
            return "There was an error"
    else:
        sys.path.append('/path_to_your_django_site/')
        os.environ['DJANGO_SETTINGS_MODULE'] = 'your_django_site.settings'
        import django.core.handlers.wsgi
        handler = django.core.handlers.wsgi.WSGIHandler()
        return handler(environ, start_response)

application = fck_handler