Come usi il caricamento delle immagini e il browser di FCKEditor con mod-wsgi?
Domanda
Sto usando FCKEditor all'interno di un'app Django servita da Apache / mod-wsgi. Non voglio installare php solo per FCKEditor e vedo che FCKEditor offre il caricamento e la navigazione delle immagini tramite Python. Non ho trovato buone istruzioni su come impostare tutto.
Quindi attualmente Django sta eseguendo un'interfaccia wsgi usando questa configurazione:
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()
In fckeditor nella directory editor- > filemanager- > connettori- > py c'è un file chiamato 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()
Ho bisogno di queste due cose che lavorano insieme, modificando il mio file django wsgi per servire correttamente le parti di fckeditor o fare in modo che apache serva correttamente sia django che fckeditor su un singolo dominio.
Soluzione 2
Modifica: alla fine non ero soddisfatto di questa soluzione, quindi ho realizzato una app Django che si occupa del caricamento dei file e della navigazione.
Questa è la soluzione che ho finalmente hackerato insieme dopo aver letto il codice 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
Altri suggerimenti
Descrive come incorporare l'editor FCK e abilitare il caricamento delle immagini.
Per prima cosa devi modificare fckconfig.js per cambiare il caricamento dell'immagine URL per puntare a qualche URL all'interno del tuo server.
FCKConfig.ImageUploadURL = "/myapp/root/imageUploader";
Questo indicherà l'URL relativo del server per ricevere il caricamento. FCK invierà il file caricato a quel gestore utilizzando la variabile CGI nome " NewFile " codificato utilizzando multipart / form-data. Sfortunatamente tu dovrà implementare / myapp / root / imageUploader, perché non credo il materiale di distribuzione FCK può essere facilmente adattato ad altri framework.
ImageUploader dovrebbe estrarre il NewFile e memorizzarlo da qualche parte sul server. La risposta generata da / myapp / root / imageUploader dovrebbe emulare l'HTML creato in /editor/.../fckoutput.py. Qualcosa del genere (formato modello 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>
I {{env ...}} elementi in alto indicano il tipo di contenuto e intestazioni HTTP consigliate da inviare. Il fileUrl dovrebbe essere l'Url a usare per trovare l'immagine sul server.
Ecco i passaggi di base per ottenere il frammento HTML che genera il widget dell'editor FCK. L'unica parte difficile è che devi mettere il corretta identificazione del client in os.environ - è brutta ma è così che funziona la libreria FCK in questo momento (ho archiviato un bug relazione).
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
Quanto sopra non è testato, ma si basa su quello sotto testato.
Ecco come usare l'editor FCK usando mod-wsgi: Tecnicamente utilizza un paio di funzionalità di WHIFF (vedi WHIFF.sourceforge.net ), - infatti fa parte della distribuzione WHIFF - ma le funzionalità WHIFF possono essere facilmente rimosse.
Non so come installarlo in Django, ma se Django consente di installare facilmente le app wsgi dovrebbe essere in grado di farlo.
NOTA: FCK consente al client di iniettare praticamente qualsiasi cosa nelle pagine HTML: vorrai filtrare il valore restituito per male attacchi. (es: consultare whiff.middleware.TestSafeHTML middleware per un esempio di come farlo).
""" 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()
Vedi questo funzionante, per esempio, su http://aaron.oirt.rutgers.edu/myapp/ docs / W1500.whyIsWhiffCool .
btw: grazie. Avevo bisogno di esaminare comunque questo.