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

editor-> filemanager-> connectors-> 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つのことを連携させる必要があります。

役に立ちましたか?

解決 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エディターを埋め込み、画像のアップロードを有効にする方法について説明します。

まず、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。 このようなもの(テンプレート形式)

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

btw:ありがとう。とにかくこれを調べる必要がありました。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top