def main(): logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) url_map = SessionMiddleware(urlmap, session_class=InMemorySession) print 'Serving on port: 8080' make_server('localhost', 8080, url_map).serve_forever()
def make_app(global_conf=None): from athemeweb.classpublisher import ClassPublisher from athemeweb.webroot import WebRoot real_app = ClassPublisher(WebRoot()) from paste.exceptions.errormiddleware import ErrorMiddleware error_app = ErrorMiddleware(real_app, global_conf=global_conf) from paste.session import SessionMiddleware return SessionMiddleware(error_app, global_conf=global_conf)
def __init__(self, root_obj, cfg): global thread_data #Session config if cfg.has_key('session'): ses_cfg = cfg['session'] ses_kw = {'cookie_name': ses_cfg.get('cookie_name', 'AmiWeb')} if ses_cfg.get('type') == 'File': ses_kw['session_class'] = FileSession ses_kw['session_file_path'] = ses_cfg.get('storage_path') else: ses_kw['session_class'] = None else: ses_kw = {} ses_kw['session_expiration'] = 60 * 336 #14 days ses_kw['expiration'] = 60 * 384 SessionMiddleware.cleanup_cycle = datetime.timedelta(seconds=360 * 60) #6 hours #Database configuration if cfg.has_key('db_pool'): global db_pool self.use_db = True db_pool = cfg['db_pool'] #print "[amiweb]RootController:cfg DOES have key db pool<br>" else: self.use_db = False #print "[amiweb]RootController:cfg does NOT have key db pool<br>" self.dispatcher = Dispatcher(root_obj, self) wsgi_app = self.dispatcher thread_data.session = SessionMiddleware(wsgi_app, **ses_kw) #wsgi_app = SessionMiddleware(wsgi_app, **ses_kw) wsgi_app = thread_data.session self.static_handler = StaticMiddleware(wsgi_app, self.dispatcher) #wsgi_app = self.static_handler if cfg.has_key('static_paths'): static_paths = cfg['static_paths'] for k in static_paths: self.addStaticPath(k, static_paths[k]) #if cfg.get('log_paths', True): # wsgi_app = translogger.TransLogger(wsgi_app, logger_name="amiweb") global config config = cfg self.wsgi_app = wsgi_app self.root_obj = root_obj
def muntjac(application, host='localhost', port=8880, nogui=False, debug=False, serve=True, forever=True, servletClass=None, *args, **kw_args): if servletClass is None: servletClass = ApplicationServlet level = logging.DEBUG if debug else logging.INFO logging.basicConfig(stream=sys.stdout, level=level, format='%(levelname)s: %(message)s') wsgi_app = servletClass(application, debug=debug, *args, **kw_args) wsgi_app = SessionMiddleware(wsgi_app, session_class=InMemorySession) url = 'http://%s:%d/' % (host, port) if nogui == False: webbrowser.open(url, new=0) httpd = make_server(host, port, wsgi_app) if serve: print 'Serving at: %s' % url if forever: # Respond to requests until process is killed httpd.serve_forever() else: # Serve one request, then exit httpd.handle_request()
body = body.encode('utf8') return [body] else: return [b'no-info'] if pi in ('/put1', '/put2'): if pi == '/put1': sess = environ['paste.session.factory']() sess['info'] = info[0] start_response('200 OK', [('content-type', 'text/plain')]) if pi == '/put2': sess = environ['paste.session.factory']() sess['info'] = info[0] return [b'foo'] wsgi_app = SessionMiddleware(wsgi_app) def test_app1(): app = TestApp(wsgi_app) res = app.get('/get1') assert res.body == b'no-info' res = app.get('/get2') assert res.body == b'no-info' info[:] = ['test'] res = app.get('/put1') res = app.get('/get1') assert res.body == b'test' res = app.get('/get2') assert res.body == b'test'
def app(environ, start_response): # Except error if 'error' in environ['PATH_INFO'].lower(): raise Exception('Detect "error" in URL path') # Session session = environ.get('paste.session.factory', lambda: {})() if 'count' in session: count = session['count'] else: count = 1 session['count'] = count + 1 # Generate response start_response('200 OK', [('Content-Type', 'text/plain')]) return ['You have been here %d times!\n' % count, ] app = EvalException(app) # go to http://localhost:8000/Errors app = SessionMiddleware(app) app = GzipMiddleware(app) app = PonyMiddleware(app) # go to http://localhost:8000/pony if __name__ == '__main__': from paste import reloader from paste.httpserver import serve reloader.install() serve(app, host='0.0.0.0', port=8000)
<Location /hello> SetHandler python-program PythonHandler paste.modpython PythonPath "['/path/to/muntjac'] + sys.path" PythonOption wsgi.application muntjac.demo.modpython::hello_app PythonOption SCRIPT_NAME /hello </Location> Alias /VAADIN "/path/to/VAADIN" <Location "/VAADIN"> SetHandler None </Location> </VirtualHost> """ from paste.session import SessionMiddleware from muntjac.demo.util import MuntjacFileSession from muntjac.demo.main import hello, calc, address, tunes, sampler hello_app = SessionMiddleware(hello, session_class=MuntjacFileSession) calc_app = SessionMiddleware(calc, session_class=MuntjacFileSession) address_app = SessionMiddleware(address, session_class=MuntjacFileSession) tunes_app = SessionMiddleware(tunes, session_class=MuntjacFileSession) sampler_app = SessionMiddleware(sampler, session_class=MuntjacFileSession)
def custom_validator_form(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) from webob import Request request = Request(environ) session = get_session(request) session['csrf'] = get_csrf_token(session) schema = Contact().bind(request=request) form = deform.Form(schema, buttons=('submit', )) template = env.get_template('simple_with_css.html') if request.POST: submitted = request.POST.items() try: form.validate(submitted) except deform.ValidationFailure as e: return template.render(form=e.render()).encode("utf-8") session.pop('csrf') return template.render(form='OK') return template.render(form=form.render()).encode("utf-8") if __name__ == '__main__': from paste.httpserver import serve from paste.session import SessionMiddleware app = SessionMiddleware(custom_validator_form) serve(app, host='0.0.0.0', port=8000)
def main(args=sys.argv[1:]): parser = OptionParser(usage='usage: muntjac [options]', version='Muntjac Version %s' % '@VERSION@') parser.add_option('-t', '--test', action='store_true', help='run tests and exit') parser.add_option('--host', default='localhost', type='string', help='WSGI server hostname') parser.add_option('--port', default=8080, type='int', help='WSGI server port number') parser.add_option('--nogui', action='store_true', default=False, help='do not open browser window') parser.add_option('--debug', action='store_true', help='run in debug mode') parser.add_option('--contextRoot', default='', type='string', help='path to VAADIN directory') opts, args = parser.parse_args(args) level = logging.DEBUG if opts.debug else logging.INFO logging.basicConfig(stream=sys.stdout, level=level, format='%(levelname)s: %(message)s') if opts.test: test() else: nargs = len(args) if nargs > 0: sys.stderr.write('Too many arguments') parser.print_help() sys.exit(2) rootapp = FileApp(join(dirname(__file__), 'public', 'index.html')) cssapp = DirectoryApp(join(dirname(__file__), 'public', 'css')) imgapp = DirectoryApp(join(dirname(__file__), 'public', 'img')) urlmap['/'] = rootapp urlmap['/css'] = cssapp urlmap['/img'] = imgapp if opts.contextRoot: ctxapp = DirectoryApp(join(opts.contextRoot, 'VAADIN')) urlmap['/VAADIN'] = ctxapp app = SessionMiddleware(urlmap, session_class=InMemorySession) url = 'http://%s:%d/' % (opts.host, opts.port) if not opts.nogui: webbrowser.open(url, new=0) print 'Serving at: %s' % url httpd = make_server(opts.host, opts.port, app) try: httpd.serve_forever() except KeyboardInterrupt: print "\nExiting" sys.exit(0)