Pregunta

Estoy usando FCKEditor dentro de una aplicación Django servida por Apache / mod-wsgi. No quiero instalar php solo para FCKEditor y veo que FCKEditor ofrece carga de imágenes y exploración de imágenes a través de Python. Simplemente no he encontrado buenas instrucciones sobre cómo configurar todo esto.

Entonces, actualmente Django se está ejecutando a través de una interfaz wsgi usando esta configuración:

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

En fckeditor en el editor- > filemanager- > connector- > py directorio hay un archivo llamado 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()

Necesito que estas dos cosas funcionen juntas mediante la modificación de mi archivo django wsgi para que sirva las partes del fckeditor correctamente o hacer que apache sirva tanto a django como fckeditor correctamente en un solo dominio.

¿Fue útil?

Solución 2

Editar: finalmente no estaba contento con esta solución, así que hice una aplicación Django que se encarga de la carga y navegación de archivos.

Esta es la solución que finalmente pirateé después de leer el código del 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

Otros consejos

Esto describe cómo incrustar el editor FCK y habilitar la carga de imágenes.

Primero necesita editar fckconfig.js para cambiar la carga de la imagen URL para apuntar a alguna URL dentro de su servidor.

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

Esto apuntará a la URL relativa del servidor para recibir la carga. FCK enviará el archivo cargado a ese controlador utilizando la variable CGI nombre " NewFile " codificado usando multipart / form-data. Desafortunadamente tu tendrá que implementar / myapp / root / imageUploader, porque no creo el material de distribución de FCK se puede adaptar fácilmente a otros marcos.

El imageUploader debe extraer el NewFile y almacenarlo en algún lugar del servidor La respuesta generada por / myapp / root / imageUploader debería emular el HTML construido en /editor/.../fckoutput.py. Algo así (formato de plantilla 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>

Las cosas {{env ...}} en la parte superior indican el tipo de contenido y Encabezados HTTP recomendados para enviar. FileUrl debe ser la URL para use para encontrar la imagen en el servidor.

Estos son los pasos básicos para obtener el fragmento html que genera el widget del editor FCK. La única parte difícil es que tienes que poner el identificación correcta del cliente en el entorno os. - es feo pero así es como funciona la biblioteca FCK en este momento (presenté un error informe).

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

Lo anterior no se ha probado, pero se basa en lo siguiente que se prueba.

Aquí está cómo usar el editor FCK usando mod-wsgi: Técnicamente utiliza un par de características de WHIFF (ver WHIFF.sourceforge.net ), - de hecho es parte de la distribución WHIFF -  pero Las características de WHIFF se eliminan fácilmente.

No sé cómo instalarlo en Django, pero si Django permite que las aplicaciones wsgi se instalen fácilmente, usted debería poder hacerlo.

NOTA: FCK permite que el cliente inyecte casi cualquier cosa en páginas HTML: querrás filtrar el valor devuelto por mal ataques (por ejemplo: consulte whiff.middleware.TestSafeHTML middleware para un ejemplo de cómo hacer esto).

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

Vea esto trabajando, por ejemplo, en http://aaron.oirt.rutgers.edu/myapp/ docs / W1500.whyIsWhiffCool .

por cierto: gracias. Necesitaba investigar esto de todos modos.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top