view MoinMoin/request/ @ 647:bebe1a6eac56

add some missing imports in request/*
author Thomas Waldmann <tw AT waldmann-edv DOT de>
date Mon, 15 May 2006 19:23:27 +0200
parents 80d0ad85a2d8
children 54b8e7d068d9
line wrap: on
line source

# -*- coding: iso-8859-1 -*-
    MoinMoin - Twisted Request Implementation

    @copyright: 2001-2003 by Jürgen Hermann <>,
                2003-2006 MoinMoin:ThomasWaldmann
    @license: GNU GPL, see COPYING for details.
import sys, os

from MoinMoin import config
from MoinMoin.request import RequestBase

class Request(RequestBase):
    """ specialized on Twisted requests """

    def __init__(self, twistedRequest, pagename, reactor, properties={}):
            self.twistd = twistedRequest
            self.reactor = reactor
            # Copy headers
            self.http_accept_language = self.twistd.getHeader('Accept-Language')
            self.saved_cookie = self.twistd.getHeader('Cookie')
            self.http_user_agent = self.twistd.getHeader('User-Agent')
            # Copy values from twisted request
            self.server_protocol = self.twistd.clientproto
            self.server_name = self.twistd.getRequestHostname().split(':')[0]
            self.server_port = str(self.twistd.getHost()[2])
            self.is_ssl = self.twistd.isSecure()
            self.path_info = '/' + '/'.join([pagename] + self.twistd.postpath)
            self.request_method = self.twistd.method
            self.remote_host = self.twistd.getClient()
            self.remote_addr = self.twistd.getClientIP()
            self.request_uri = self.twistd.uri
            self.script_name = "/" + '/'.join(self.twistd.prepath[:-1])

            # Values that need more work
            self.query_string = self.splitURI(self.twistd.uri)[1]

            RequestBase.__init__(self, properties)

        except MoinMoinFinish: # might be triggered by http_redirect
            self.http_headers() # send headers (important for sending MOIN_ID cookie)

        except Exception, err:
            # Wrap err inside an internal error if needed
            from MoinMoin import error
            if isinstance(err, error.FatalError):
                self.delayedError = err
                self.delayedError = error.InternalError(str(err))

    def run(self):
        """ Handle delayed errors then invoke base class run """
        if hasattr(self, 'delayedError'):
            return self.finish()
    def setup_args(self, form=None):
        """ Return args dict 
        Twisted already parsed args, including __filename__ hacking,
        but did not decode the values.
        # TODO: check if for a POST this included query_string args (needed for
        # TwikiDraw's action=AttachFile&do=savedrawing)
        return self.decodeArgs(self.twistd.args)
    def read(self, n=None):
        """ Read from input stream. """
        # XXX why is that wrong?:
        #rd = self.reactor.callFromThread(
        # XXX do we need self.reactor.callFromThread with that?
        # XXX if yes, why doesn't it work?, 0)
        if n is None:
            rd =
            rd =
        #print " data=\n" + str(rd)
        return rd
    def write(self, *data):
        """ Write to output stream. """
        #print "request.RequestTwisted.write: data=\n" + wd
        self.reactor.callFromThread(self.twistd.write, self.encode(data))

    def flush(self):
        pass # XXX is there a flush in twisted?

    def finish(self):

    def open_logs(self):
        # create log file for catching stderr output
        if not self.opened_logs:
            sys.stderr = open(os.path.join(self.cfg.data_dir, 'error.log'), 'at')
            self.opened_logs = 1

    # Headers ----------------------------------------------------------

    def __setHttpHeader(self, header):
        if type(header) is unicode:
            header = header.encode('ascii')
        key, value = header.split(':', 1)
        value = value.lstrip()
        if key.lower() == 'set-cookie':
            key, value = value.split('=', 1)
            self.twistd.addCookie(key, value)
            self.twistd.setHeader(key, value)
        #print "request.RequestTwisted.setHttpHeader: %s" % header

    def http_headers(self, more_headers=[]):
        if getattr(self, 'sent_headers', None):
        self.sent_headers = 1
        have_ct = 0

        # set http headers
        for header in more_headers + getattr(self, 'user_headers', []):
            if header.lower().startswith("content-type:"):
                # don't send content-type multiple times!
                if have_ct: continue
                have_ct = 1

        if not have_ct:
            self.__setHttpHeader("Content-type: text/html;charset=%s" % config.charset)

    def http_redirect(self, url):
        """ Redirect to a fully qualified, or server-rooted URL 
        @param url: relative or absolute url, ascii using url encoding.
        url = self.getQualifiedURL(url)
        # calling finish here will send the rest of the data to the next
        # request. leave the finish call to run()
        raise MoinMoinFinish

    def setResponseCode(self, code, message=None):
        self.twistd.setResponseCode(code, message)