Comment utilisez-vous le téléchargement d'images et le navigateur de FCKEditor avec mod-wsgi?

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

Question

J'utilise FCKEditor dans une application Django servie par Apache / mod-wsgi. Je ne veux pas installer php juste pour FCKEditor et je vois que FCKEditor propose le téléchargement et la navigation d'images à travers Python. Je n'ai tout simplement pas trouvé de bonnes instructions sur la façon de régler tout cela.

Django fonctionne donc actuellement via une interface wsgi en utilisant cette configuration:

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

Dans fckeditor, dans le répertoire editor- > filemanager- > connecteurs- > py, il existe un fichier appelé 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()

J'ai besoin de ces deux choses pour que deux fonctionnent ensemble en modifiant mon fichier wsgi de django pour servir correctement les parties de fckeditor ou pour que apache serve correctement django et fckeditor sur un même domaine.

Était-ce utile?

La solution 2

Éditer: cette solution n’a finalement pas donné satisfaction, j’ai donc créé une application Django . qui prend en charge les téléchargements de fichiers et la navigation.

C’est la solution que j’ai finalement piratée ensemble après avoir lu le code de l’éditeur:

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

Autres conseils

Ceci décrit comment incorporer l'éditeur FCK et activer le téléchargement d'images.

Vous devez d’abord éditer fckconfig.js pour changer le téléchargement d’image. URL permettant de pointer sur une URL du serveur.

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

Ceci pointera sur l'URL relative du serveur pour recevoir le téléchargement. FCK enverra le fichier téléchargé à ce gestionnaire en utilisant la variable CGI nom " NewFile " codé en utilisant multipart / form-data. Malheureusement toi devra implémenter / myapp / root / imageUploader, car je ne pense pas la distribution FCK peut être facilement adaptée à d’autres frameworks.

imageUploader doit extraire le NewFile et le stocker quelque part sur le serveur. La réponse générée par / myapp / root / imageUploader doit émuler le code HTML construit dans /editor/.../fckoutput.py. Quelque chose comme ça (format 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>

Les éléments {{env ...}} en haut indiquent le type de contenu et en-têtes HTTP recommandés à envoyer. FileUrl doit être l'URL à utiliser pour trouver l'image sur le serveur.

Voici les étapes de base pour obtenir le fragment HTML qui génère le widget éditeur FCK. Le seul problème est que vous devez mettre le bonne identification du client dans os.environ - c'est moche mais c’est ainsi que fonctionne la bibliothèque FCK (j’ai déposé un bogue rapport).

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

Ce qui précède n'a pas été testé, mais il est basé sur ce qui est testé ci-dessous.

Voici comment utiliser l'éditeur FCK en utilisant mod-wsgi: Techniquement, il utilise quelques fonctionnalités du WHIFF (voir WHIFF.sourceforge.net ), - En fait, cela fait partie de la distribution WHIFF -  mais les caractéristiques WHIFF sont facilement supprimées.

Je ne sais pas comment l'installer dans Django, mais si Django permet aux applications wsgi d'être installées facilement, vous devrait être capable de le faire.

NOTE: FCK permet au client d’injecter à peu près n'importe quoi en pages HTML - vous voudrez filtrer la valeur renvoyée pour le mal attaques. (par exemple, voir le middleware whiff.middleware.TestSafeHTML pour un exemple de la façon de le faire).

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

Voir cela fonctionne, par exemple, à http://aaron.oirt.rutgers.edu/myapp/ docs / W1500.whyIsWhiffCool .

btw: merci. Je devais quand même me pencher sur la question.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top