如何在mod-wsgi中使用FCKEditor的图像上传和浏览功能?
我在一个用Django做的应用里使用FCKEditor,服务器是Apache加上mod-wsgi。我不想为了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。
2 个回答
这段内容讲的是如何嵌入FCK编辑器并启用图片上传功能。
首先,你需要编辑fckconfig.js文件,把图片上传的地址改成你服务器上的某个地址。
FCKConfig.ImageUploadURL = "/myapp/root/imageUploader";
这个地址会指向服务器上接收上传的路径。FCK会用一个叫“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应该是用来在服务器上找到图片的地址。
下面是获取生成FCK编辑器小部件的HTML片段的基本步骤。唯一麻烦的地方是你需要把正确的客户端识别信息放入os.environ中——这看起来不太好,但目前FCK库就是这样工作的(我已经提交了一个bug报告)。
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。
顺便说一下:谢谢你。我本来就需要研究这个。
补充说明:最后我对这个解决方案也不满意,所以我做了一个Django应用,专门处理文件上传和浏览。
这是我在阅读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