mod-wsgi와 함께 fckeditor의 이미지 업로드 및 브라우저를 어떻게 사용합니까?

StackOverflow https://stackoverflow.com/questions/803613

문제

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

편집 : 궁극적으로 나는이 솔루션에도 불만이 있었기 때문에 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

다른 팁

이것은 FCK 편집기를 포함하고 이미지 업로드를 활성화하는 방법을 설명합니다.

먼저 서버 내부의 일부 URL을 가리 키도록 이미지 업로드 URL을 변경하려면 FCKCONFIG.JS를 편집해야합니다.

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

이는 서버 상대 URL이 업로드를 수신하도록 지적합니다. FCK는 Multipart/Form-Data를 사용하여 인코딩 된 CGI 변수 이름 "NewFile"을 사용하여 업로드 된 파일을 해당 핸들러에 보냅니다. 불행히도 FCK 배포 항목이 다른 프레임 워크에 쉽게 조정할 수 없다고 생각하기 때문에/myapp/root/imageUploader를 구현해야합니다.

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이어야합니다.

다음은 FCK 편집기 위젯을 생성하는 HTML 조각을 얻는 기본 단계입니다. 유일한 까다로운 부분은 올바른 클라이언트 계약을 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.

BTW : 감사합니다. 어쨌든 이것을 조사해야했습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top