【问题标题】:How do you use FCKEditor's image upload and browser with mod-wsgi?FCKEditor 的图片上传和浏览器如何配合 mod-wsgi 使用?
【发布时间】:2009-04-29 18:23:30
【问题描述】:

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

在fckeditor的editor->filemanager->connectors->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 提供正确的服务,从而使这两件事协同工作。

【问题讨论】:

    标签: python django fckeditor mod-wsgi


    【解决方案1】:

    这描述了如何嵌入 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。 像这样的东西(气味模板格式)

    {{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 页面——你会想要过滤返回值是否为 evil 攻击。 (例如:参见 whiff.middleware.TestSafeHTML 中间件 如何执行此操作的示例)。

    """ 引入 FCK 编辑器输入元素。 (需要 FCKeditor http://www.fckeditor.net/)。 注意:这个实现可以生成包含代码注入攻击的值,如果你 不要过滤为邪恶标签和值生成的输出。 """ import fckeditor # 你必须安装 fck 编辑器 python 支持才能使用这个模块 从 whiff.middleware 导入杂项 导入操作系统 FCKInput 类(misc.utility): def __init__(self, inputName, # 输入元素的名称 basePath, # 用于 FCK HTTP 安装的服务器相对 URL 根 value = ""): # 输入的初始值 self.inputName = 输入名称 self.basePath = basePath 自我价值=价值 def __call__(self, env, start_response): inputName = self.param_value(self.inputName, env).strip() basePath = self.param_value(self.basePath, env).strip() 如果 basePath[-1:]!="/": 基本路径+="/" value = self.param_value(self.value, env) oFCKeditor = fckeditor.FCKeditor(inputName) oFCKeditor.BasePath = basePath oFCKeditor.Height = 300 # 这应该是必需的! oFCKeditor.Value = 值 # 破解 fck python 库中的一个错误:需要将用户代理放入 os.environ # XXX 这个 hack 对于多线程服务器是不安全的(理论上)...需要锁定 os.env os_environ = os.environ new_os_env = os_environ.copy() new_os_env.update(env) 尝试: os.environ = new_os_env htmlOut = oFCKeditor.Create() 最后: # 恢复旧的 os.environ os.environ = os_environ start_response("200 OK", [('Content-Type', 'text/html')]) 返回 [htmlOut] __middleware__ = FCKInput 定义测试(): 环境 = { “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", "开始的 HTML 值") r = f(env, misc.ignore) 打印“测试结果” 打印“”。加入(列表(r)) 如果 __name__=="__main__": 测试()

    查看这个工作,例如,在 http://aaron.oirt.rutgers.edu/myapp/docs/W1500.whyIsWhiffCool.

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

    【讨论】:

      【解决方案2】:

      编辑:最终我对这个解决方案也不满意,所以我创建了一个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
      

      【讨论】:

        猜你喜欢
        • 2017-07-07
        • 2014-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-24
        • 2015-01-25
        相关资源
        最近更新 更多