Ejemplo n.º 1
0
 def log(self, msg):
     if self.logger.error_log is self.__error_log:
         try:
             self.__apache_request.log_error(msg)
         except AttributeError:
             apache.log_error(msg)
     else:
         Publisher.log(self, msg)
Ejemplo n.º 2
0
 def log(self, msg):
     if self.logger.error_log is self.__error_log:
         try:
             self.__apache_request.log_error(msg)
         except AttributeError:
             apache.log_error(msg)
     else:
         Publisher.log(self, msg)
Ejemplo n.º 3
0
 def __init__(self, root_namespace, config=None):
     from quixote.config import Config
     if type(root_namespace) is types.StringType:
         root_namespace = _get_module(root_namespace)
     self.namespace_stack = [root_namespace]
     if config is None:
         config = Config()
     directory = RootDirectory(root_namespace, self.namespace_stack)
     _Publisher.__init__(self, directory, config=config)
Ejemplo n.º 4
0
 def __init__(self, root_namespace, config=None):
     from quixote.config import Config
     if type(root_namespace) is types.StringType:
         root_namespace = _get_module(root_namespace)
     self.namespace_stack = [root_namespace]
     if config is None:
         config = Config()
     directory = RootDirectory(root_namespace, self.namespace_stack)
     _Publisher.__init__(self, directory, config=config)
Ejemplo n.º 5
0
 def __init__(self,
              root_directory,
              logger=None,
              session_manager=None,
              config=None,
              **kwargs):
     Publisher.__init__(self, root_directory, logger, session_manager,
                        config, **kwargs)
     self._request_dict = {}
     del self._request
Ejemplo n.º 6
0
    def test_config_for_application_json_support(self):
        pub = Publisher('__main__')
        self.assertFalse(pub.config.support_application_json)

        req = pub.create_request(StringIO(), {'CONTENT_TYPE': "application/json"})
        self.assertFalse(isinstance(req, HTTPJSONRequest))

        pub.configure(SUPPORT_APPLICATION_JSON=1)

        req = pub.create_request(StringIO(), {'CONTENT_TYPE': "application/json"})
        self.assertTrue(isinstance(req, HTTPJSONRequest))
Ejemplo n.º 7
0
def create_publisher():
    """
    Create a publisher for TwillTest, with session management added on.
    """
    session_manager = SessionManager(session_class=AlwaysSession)
    return Publisher(TwillTest(),
                     session_manager=session_manager)
Ejemplo n.º 8
0
def publisher_make(main_h_obj):
    #/
    publisher = Publisher(main_h_obj,
        display_exceptions='plain'
    )
    ## Only one Publisher instance is allowed to be created.
    ## In |Publisher.__init__|, it will set variable |quixote.publish._publisher|
    ##  to the Publisher instance itself.
    ## All functions in module |quixote.publish| then operate on this |_publisher|.
    ## This explains why we can call |quixote.publish.get_request| without telling
    ## it which publisher we are referring to.

    #/
    publisher.is_thread_safe = True

    #/
    return publisher
Ejemplo n.º 9
0
    def start_request(self, request):
        Publisher.start_request(self, request)
        os.environ['SQLSTORE_SOURCE'] = request.get_url()

        resp = request.response
        resp.set_content_type('text/html; charset=utf-8')
        resp.set_header('Pragma', 'no-cache')
        resp.set_header('Cache-Control', 'must-revalidate, no-cache, private')
        # FIXME: quixote with origin?
        resp.set_header('Access-Control-Allow-Origin', '*')
        request.enable_ajax = False
        request.browser = request.guess_browser_version()
        request.method = request.get_method()
        request.url = request.get_path()
        request.is_mobile = is_mobile_device(request)
        request.start_time = time.time()
        request.user = User.check_session(request)

        import_obj_set("request", request)
Ejemplo n.º 10
0
def main():
    from quixote import enable_ptl
    enable_ptl()

    if len(sys.argv) == 2:
        port = int(sys.argv[1])
    else:
        port = 8080
    print 'Now serving the Quixote demo on port %d' % port
    server = http_server.http_server('', port)
    publisher = Publisher('quixote.demo')

    # When initializing the Publisher in your own driver script,
    # you'll want to parse a configuration file.
    ##publisher.read_config("/full/path/to/demo.conf")
    publisher.setup_logs()
    dh = QuixoteHandler(publisher, 'Quixote/demo', server)
    server.install_handler(dh)
    asyncore.loop()
Ejemplo n.º 11
0
    def start_request(self, request):
        Publisher.start_request(self, request)
        os.environ['SQLSTORE_SOURCE'] = request.get_url()

        resp = request.response
        resp.set_content_type('text/html; charset=utf-8')
        resp.set_header('Pragma', 'no-cache')
        resp.set_header('Cache-Control', 'must-revalidate, no-cache, private')
        # FIXME: quixote with origin?
        resp.set_header('Access-Control-Allow-Origin', '*')
        request.enable_ajax = False
        request.browser = request.guess_browser_version()
        request.method = request.get_method()
        request.url = request.get_path()
        request.is_mobile = is_mobile_device(request)
        request.start_time = time.time()
        request.user = User.check_session(request)

        import_obj_set("request", request)
Ejemplo n.º 12
0
def main():
    from quixote import enable_ptl
    enable_ptl()

    if len(sys.argv) == 2:
        port = int(sys.argv[1])
    else:
        port = 8080
    print 'Now serving the Quixote demo on port %d' % port
    server = http_server.http_server('', port)
    publisher = Publisher('quixote.demo')

    # When initializing the Publisher in your own driver script,
    # you'll want to parse a configuration file.
    ##publisher.read_config("/full/path/to/demo.conf")
    publisher.setup_logs()
    dh = QuixoteHandler(publisher, 'Quixote/demo', server)
    server.install_handler(dh)
    asyncore.loop()
Ejemplo n.º 13
0
def create_publisher(coordinator, pubsubhubbub_server=None):
    push_list = []
    if pubsubhubbub_server:
        push_list.append(pubsubhubbub_server)
        
    qx_app = QuixoteWebApp(coordinator, push_list)
    
    # sets global Quixote publisher
    Publisher(qx_app, display_exceptions='plain')

    # return a WSGI wrapper for the Quixote Web app.
    return quixote.get_wsgi_app()
Ejemplo n.º 14
0
def main():

    out = sys.stdout
    sys.stdout = EmptyFile()
    sys.stderr = EmptyFile()

    # session handling
    sessionPickle = SessionPickle(config.sessionsPickleFile)
    sessions = sessionPickle.loadSessions()
    sessMgr = SessionManager(session_class=MySession, session_mapping=sessions)

    directory = AlineaDirectory()
    conf = Config()
    conf.read_file(CONFIG)
    publisher = Publisher(directory, session_manager=sessMgr, config=conf)

    request = HTTPRequest(sys.stdin, os.environ)
    response = publisher.process_request(request)

    response.write(out)

    sessionPickle.saveSessions(sessMgr.sessions)
Ejemplo n.º 15
0
 def create_durus_publisher():
     global connection
     filename = os.path.join(tempfile.gettempdir(), 'quixote-demo.durus')
     print('Opening %r as a Durus database.' % filename)
     connection = Connection(FileStorage(filename))
     root = connection.get_root()
     session_manager = root.get('session_manager', None)
     if session_manager is None:
         session_manager = PersistentSessionManager()
         connection.get_root()['session_manager'] = session_manager
         connection.commit()
     return Publisher(RootDirectory(),
                      session_manager=session_manager,
                      display_exceptions='plain')
Ejemplo n.º 16
0
    def test_config_for_application_json_support(self):
        pub = Publisher('__main__')
        self.assertFalse(pub.config.support_application_json)

        req = pub.create_request(StringIO(),
                                 {'CONTENT_TYPE': "application/json"})
        self.assertFalse(isinstance(req, HTTPJSONRequest))

        pub.configure(SUPPORT_APPLICATION_JSON=1)

        req = pub.create_request(StringIO(),
                                 {'CONTENT_TYPE': "application/json"})
        self.assertTrue(isinstance(req, HTTPJSONRequest))
Ejemplo n.º 17
0
    def download(self, fname):
        self.out.write("BEGIN %s" % fname)
        for line in file(fname):
            time.sleep(.1)
            self.out.write(".")
            yield None
        self.out.write(" END %s\n" % fname)

    def quit(self, fd):
        self.lc.stop()
        reactor.callLater(1, self.stop)  # shutdown in 1 second
        return "shutdown in 1 second ..."

    def stop(self):
        self.out.close()
        reactor.stop()


class Home(Directory):
    _q_exports = ["micheles", "pippo"]
    micheles = Interaction()  # in principle reserved to user micheles
    pippo = Interaction()  # in principle reserved to user pippo


if __name__ == '__main__':
    from quixote.server import twisted_server
    c = Controller('localhost', 7080, twisted_server.run)
    reactor.callLater(1, c.open_browser, "micheles/downloader")
    c.run(lambda: Publisher(Home()))
Ejemplo n.º 18
0
def create_publisher():
    return Publisher(RootDirectory(),
                     error_log="/logs/%s_err.log" % pname,
                     access_log="/logs/%s_acc.log" % pname,
                     display_exceptions="plain")
Ejemplo n.º 19
0
def create_publisher():
    "Create & return a test publisher entry"
    p = Publisher(TestServer())
    p.is_thread_safe = True

    return p
Ejemplo n.º 20
0
 def __init__(self, *args, **kw):
     Publisher.__init__(self, *args, **kw)
     self._request_dict = {}
Ejemplo n.º 21
0
 def try_publish(self, request, path):
     output = Publisher.try_publish(self, request, path)
     output = show_performance_metric(request, output)
     return output
Ejemplo n.º 22
0
def create_publisher():
    return Publisher(RootDirectory(),
                     session_manager=SessionManager(session_class=DemoSession),
                     display_exceptions='plain')
Ejemplo n.º 23
0
 def __init__(self, package, **kwargs):
     Publisher.__init__(self, package, **kwargs)
     # may be overwritten
     self.logger.error_log = self.__error_log = ErrorLog(self)
     self.__apache_request = None
Ejemplo n.º 24
0
 def finish_failed_request(self, request):
     if DEVELOP_MODE:
         exc_type, exc_value, tb = sys.exc_info()
         raise exc_type, exc_value, tb
     else:
         return Publisher.finish_failed_request(self, request)
Ejemplo n.º 25
0
 def try_publish(self, request, path):
     output = Publisher.try_publish(self, request, path)
     output = show_performance_metric(request, output)
     return output
Ejemplo n.º 26
0
def selector(songs):
    global player, song
    chosen = get_field("select")
    if chosen:
        song = chosen
        player = play(song)
        redirect("stopper") # works with Mozilla, but not with lynx/elinks
    else:
        f = Form()
        f.add_single_select("select", options=songs)
        f.add_submit("play", "Play!")
        return f.render()

def stopper():
    stop = get_field("stop")
    if stop:
        player.kill()
        return simplepage(body = "%s stopped." % song)
    else:
        f = Form()
        f.add_submit("stop", "Stop")
        return simplepage(body= ("Playing %s" % song) +
                          f.render())

top.stopper = lambda : stopper()

if __name__ == '__main__':
    print 'Listening on http://localhost:8080 ...'
    run(lambda : Publisher(top), '', 8080)
Ejemplo n.º 27
0
def factory():
    return Publisher(MySite())
Ejemplo n.º 28
0
def create_publisher():
    "Create & return a test publisher entry"
    p = Publisher(TestServer())
    p.is_thread_safe = True

    return p
Ejemplo n.º 29
0
    def process_request (self, request, env):
        from quixote.publish import Publisher      

        url = request.get_url()
        method = request.get_method()        
        
        try:
            has_profile_request = (request.environ['QUERY_STRING'].find('__profile') != -1)
        except:
            has_profile_request = False

        # if has_profile_request or (('/edit' in url) and (method=='POST')) or ('.xml' in url):
        # if has_profile_request or (('/edit' in url) and (method=='POST')):                    
        if has_profile_request:       
            import sys, os, hotshot, hotshot.stats
            import cStringIO
            
            file_name = os.tempnam('/var/tmp', 'scgi.prof.')
            
            prof = hotshot.Profile(file_name)
            result = prof.runcall(Publisher.process_request, self, request, env)
            prof.close()
            
            stats = hotshot.stats.load(file_name).strip_dirs().sort_stats("cumulative")
            os.unlink(file_name)
            
            stats_io = cStringIO.StringIO()
            save_stdout = sys.stdout
            sys.stdout = stats_io
            stats.print_stats(100)
            sys.stdout = save_stdout
            
            from qon.util import sendmail
            sendmail("Profile Output: %s %s" % (method, url), stats_io.getvalue(), ['*****@*****.**'])
            stats_io.close()
            
            
            return result

        else:
            # for recording cache activity            
            pre_accesses = get_database().storage._cache.fc._n_accesses
            pre_adds = get_database().storage._cache.fc._n_adds            
            pre_added_bytes = get_database().storage._cache.fc._n_added_bytes
            pre_evicts = get_database().storage._cache.fc._n_evicts
            pre_evicted_bytes = get_database().storage._cache.fc._n_evicted_bytes

            # for timing each request
            start = datetime.utcnow()

            # DO IT            
            result = Publisher.process_request(self, request, env)

            # get elapsed time            
            td = datetime.utcnow() - start
            time_in_ms = td.seconds*1000 + td.microseconds/1000

            # for recording basic cache activity
            total_added_bytes = get_database().storage._cache.fc._n_added_bytes
            total_evicted_bytes = get_database().storage._cache.fc._n_evicted_bytes
            accesses = get_database().storage._cache.fc._n_accesses - pre_accesses
            adds = get_database().storage._cache.fc._n_adds - pre_adds            
            added_bytes = total_added_bytes - pre_added_bytes
            evicts = get_database().storage._cache.fc._n_evicts - pre_evicts
            evicted_bytes = total_evicted_bytes - pre_evicted_bytes            

            # log slow requests to a file (and for now, any edits)
            # if (time_in_ms > local.LOG_TIMING_MIN_MS) or (('/edit' in url) and (method=='POST')) or (random.randint(0,99)==0):
            # if (time_in_ms > local.LOG_TIMING_MIN_MS) or (('/edit' in url) and (method=='POST')):
            if (time_in_ms > local.LOG_TIMING_MIN_MS):
                if local.CACHE_INSTRUMENTATION:
                    # report detailed cache stats
                    detailed_cache_stats = get_database().storage._cache.fc.get_formatted_cache_stats()
                    qon.log.timing_info('%s\t%s\t%d ms\t(%d ac; %d a, %d ab, %d tab; %d e, %d eb, %d teb\n%s' \
                                        % (method, url, time_in_ms, accesses, adds, added_bytes, total_added_bytes, evicts, evicted_bytes, total_evicted_bytes, detailed_cache_stats))
                else:
                    # just report basic cache stats
                    qon.log.timing_info('%s\t%s\t%d ms\t(%d ac; %d a, %d ab, %d tab; %d e, %d eb, %d teb)' \
                                        % (method, url, time_in_ms, accesses, adds, added_bytes, total_added_bytes, evicts, evicted_bytes, total_evicted_bytes))

            # record histogram of times for reporting on admin page
            record_time(url, get_user(), time_in_ms)
            
                    
        if local.CACHE_INSTRUMENTATION:
            # clear out lists to ready for next call
            detailed_cache_stats = get_database().storage._cache.fc.clear_oid_lists()
            
        return result
Ejemplo n.º 30
0
 def __init__(self, *args, **kwargs):
     Publisher.__init__(self, *args, **kwargs)
     self.configure(DISPLAY_EXCEPTIONS='plain',
                    SECURE_ERRORS=0,
                    UPLOAD_DIR=get_tmpdir() + '/upload/')
Ejemplo n.º 31
0
def create_publisher():
    from quixote.demo.root import RootDirectory
    return Publisher(RootDirectory(), display_exceptions='plain')
Ejemplo n.º 32
0
def create_publisher():
    return Publisher(RootDirectory(), display_exceptions='plain')
Ejemplo n.º 33
0
 def filter_output(self, request, output):
     output = Publisher.filter_output(self, request, output)
     resp = request.response
     if resp.get_header("Content-Type") in (None, "text/html"):
         resp.set_header("Content-Type", "text/html; charset=%s" % language.encoding())
     return output
Ejemplo n.º 34
0
 def __init__ (self,root_namespace,logger=None,session_manager=None,config=None): 
     Publisher.__init__(self, root_namespace,logger,session_manager, config) 
     self._request_dict = {} 
Ejemplo n.º 35
0
 def __init__(self, *args, **kw):
     Publisher.__init__(self, *args, **kw)
     self._request_dict = {}
Ejemplo n.º 36
0
Archivo: app.py Proyecto: leonsim/me
 def __init__(self, *args, **kwargs):
     Publisher.__init__(self, *args, **kwargs)
Ejemplo n.º 37
0
 def finish_failed_request(self, request):
     if DEVELOP_MODE:
         exc_type, exc_value, tb = sys.exc_info()
         raise exc_type, exc_value, tb
     else:
         return Publisher.finish_failed_request(self, request)
Ejemplo n.º 38
0
 def __init__(self, package, **kwargs):
     Publisher.__init__(self, package, **kwargs)
     # may be overwritten
     self.logger.error_log = self.__error_log = ErrorLog(self)
     self.__apache_request = None
Ejemplo n.º 39
0
	def filter_output(self, request, output):
		output = Publisher.filter_output(self, request, output)
		#resp = request.response
		#if resp.get_header('Content-Type') in (None, 'text/html'):
		#	resp.set_header('Content-Type','text/html; charset=%s' % language.encoding() )
		return output
Ejemplo n.º 40
0
def create_publisher():
     p = Publisher(RootDirectory(), display_exceptions='plain')
     p.is_thread_safe = True
     return p
Ejemplo n.º 41
0
 def __init__(self, *args, **kwargs):
     Publisher.__init__(self, *args, **kwargs)
     self.configure(DISPLAY_EXCEPTIONS='plain',
                    SECURE_ERRORS=0,
                    UPLOAD_DIR=get_tmpdir() + '/upload/')