def test_full_pipeline(): app = Application(mock_endpoint, extensions=[DebugExtension()]) req = Request.blank('/') response = req.get_response(app) assert response.status_int == 500 assert 'by zero' in response.text
def setup_class(cls): """Construct the application to test against.""" ext = SessionExtension() cls.sessions = ext.engines['default']._sessions cls.app = Application(cls.Root, extensions=[ SerializationExtension(), ext, ]) cls.cookies = {}
def test_after_attribute_exception(self): self.app = Application.factory(root=BadController, **test_config) response, data = self.assertRPCResponse( "test", status="500 Internal Server Error", content_type="application/json" ) self.assertEquals( data, dict( id=1, result=None, error=dict( message="'BadController' object has no attribute 'nonexisting'", code=100, name="JSONRPCError", error="Not disclosed.", ), ), )
# Enable the use of cinje templates. __import__('cinje') # Doing it this way prevents an "imported but unused" warning. from web.core import Application # Get references to web framework extensions. from web.ext.annotation import AnnotationExtension from web.ext.debug import DebugExtension from web.ext.serialize import SerializationExtension from web.ext.db import DatabaseExtension # Get a reference to our database connection adapter. from web.db.mongo import MongoDBConnection # Get a reference to our WCMDB root object. from web.app.wcmdb.root import Wcmdb app = Application(Wcmdb, extensions=[ AnnotationExtension(), DebugExtension(), SerializationExtension(), DatabaseExtension(MongoDBConnection("mongodb://localhost/test")), ]) if __name__ == "__main__": app.serve('wsgiref')
app = Application( Redirect, extensions = [ AnalyticsExtension(), SerializationExtension(), DBExtension( MongoDBConnection( ENV('MONGODB_ADDON_URI', "mongodb://localhost/test") ) ), ] + ([ DebugExtension() ] if __debug__ else []), logging = { 'version': 1, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'json', 'level': 'DEBUG' if __debug__ else 'INFO', 'stream': 'ext://sys.stdout', } }, 'loggers': { 'web.app.redirect': { 'level': 'DEBUG' if __debug__ else 'INFO', 'handlers': ['console'], 'propagate': False, }, 'web': { 'level': 'DEBUG' if __debug__ else 'WARN', 'handlers': ['console'], 'propagate': False, }, }, 'root': { 'level': 'INFO' if __debug__ else 'WARN', 'handlers': ['console'] }, 'formatters': { 'json': {'()': 'marrow.mongo.util.logger.JSONFormatter'} } } )
def do(root, path_): app = Application(root) req = Request.blank(path_) return req.get_response(app)
return ", ".join([i.name for i in session.query(Foo).order_by('name').all()]) test_config = { 'debug': False, 'web.widgets': False, 'web.sessions': False, 'web.compress': False, 'web.static': False, 'db.connections': 'test', 'db.test.engine': 'sqlalchemy', 'db.test.model': RootController.__module__, 'db.test.url': 'sqlite:///:memory:' } app = Application.factory(root=RootController, **test_config) class TestSASession(WebTestCase): app = app def test_index(self): self.assertResponse('/', body='success') def test_in_session(self): response = self.assertResponse('/in_session') assert response.body.startswith('<sqlalchemy.orm.session.Session object') def test_http_exceptions(self): self.assertResponse('/http_ok', '200 OK', 'text/plain') self.assertResponse('/http_error', '500 Internal Server Error', 'text/plain')
def post(self, name="world"): return "Hello %s!" % (name,) class RootController(Controller): index = Index() if __name__ == "__main__": import logging from paste import httpserver from web.core import Application logging.basicConfig(level=logging.INFO) app = Application.factory( root=RootController, debug=False, **{ "web.sessions": False, "web.widgets": False, "web.sessions": False, "web.profile": False, "web.static": False, "web.compress": False, } ) httpserver.serve(app, host="127.0.0.1", port="8080")
#!/usr/bin/env python # encoding: utf-8 """A basic hello world application. This can be simplified down to 5 lines in total; two import lines, two controller lines, and one line to serve it. """ from web.core import Controller class RootController(Controller): def index(self): return 'Hello world!' def hello(self, name): return "Hello, %(name)s!" % dict(name=name) if __name__ == '__main__': import logging from paste import httpserver from web.core import Application logging.basicConfig(level=logging.INFO) app = Application.factory(root=RootController, debug=False) httpserver.serve(app, host='127.0.0.1', port='8080')
# encoding: utf-8 """A callable class example.""" class Root(object): def __init__(self, context): self._ctx = context def __call__(self, name): """ / -- 500 /?name=Bob / POST name=bob /Bob """ return "Hello " + name if __name__ == '__main__': from web.core import Application Application(Root).serve('wsgiref')
app = Application( Root, extensions=[ AnnotationExtension(), SerializationExtension(), GitExtension(), DJHostExtension(), DJDatabaseExtension(sessions=MongoDBConnection( config['session']['uri']), config=config), SelectiveDefaultDatabase(), DJExtension(config=config['site']), ThemeExtension(default=config['site']['default_theme']), ACLExtension(default=when.always), AuthExtension(intercept=None, name=None, session='authenticated', lookup=Auth.lookup, authenticate=Auth.authenticate), SessionExtension( secret=config['session']['secret'], expires=timedelta(days=config['session']['expires']), refresh=True, default=MongoSession(Session, database=config['session']['database']), ), LocaleExtension(), ] + ([ DebugExtension(), ] if __debug__ else []), )
__collection__ = 'sessions' value = String(default=None) class Root(object): def __init__(self, context): self._ctx = context def get(self): return repr(self._ctx.session.__data__) def set(self, value): self._ctx.session.value = value return "OK" app = Application(Root, extensions=[ DebugExtension(), DatabaseExtension(session=MongoDBConnection('mongodb://localhost/test')), SessionExtension( secret = 'xyzzy', expires = 24 * 90, default = MongoSession(Session, database='session'), ), ]) if __name__ == "__main__": app.serve('wsgiref', host='0.0.0.0', port=8080)
# Get a reference to the Application class. from web.core import Application # Get references to framework extensions. from web.ext.annotation import AnnotationExtension from web.ext.debug import DebugExtension # Get a reference to our Wiki root. from wiki.wiki import Wiki # This is our WSGI application instance. app = Application(Wiki, extensions=[ AnnotationExtension(), DebugExtension(), ]) # If we're run as the "main script", serve our application over HTTP. if __name__ == "__main__": app.serve('wsgiref')
def do(path): app = Application(Root) req = Request.blank(path) return req.get_response(app)
# encoding: utf-8 """A one-function WebCore 2 demonstration application. Applications can be as simple or as complex and layered as your needs dictate. """ def basic(context, name="world"): """Say hello. This can be tested easily using cURL from the command line: curl http://localhost:8080/ # Default value via GET. curl http://localhost:8080/Alice # Positionally specified via GET. curl -d name=Eve http://localhost:8080/ # Form-encoded value via POST. """ return "Hello {name}.".format(name=name) if __name__ == '__main__': from web.core import Application Application(basic).serve('waitress', threads=16)
# encoding: utf-8 """Template rendering sample application. This renders the test.html file contained in the current working directory. """ def template(context): context.log.info("Returning template result.") return 'mako:./template.html', dict() if __name__ == '__main__': from web.core import Application from web.ext.template import TemplateExtension # Create the underlying WSGI application, passing the extensions to it. app = Application(template, extensions=[TemplateExtension()]) # Start the development HTTP server. app.serve('wsgiref')
return dict(answer=a * b) class SampleExtension: """Here's an example of how to catch an annotation like this as a view handler.""" def start(self, context): context.view.register(tuple, self.render_json) def render_json(self, context, result): # Bail out if this isn't a 2-tuple, or isn't intended for JSON serialization. # This is an informal protocol shared with the more complete `web.template` package and possibly others. if len(result) != 2 or result[0] != 'json': return resp = context.response resp.content_type = 'application/json' resp.encoding = 'utf-8' resp.text = dumps(result[1]) return True if __name__ == '__main__': from web.core import Application from web.ext.annotation import AnnotationExtension Application(Root, extensions=[SampleExtension(), AnnotationExtension()]).serve('wsgiref')
#!/usr/bin/env python # encoding: utf-8 """A basic hello world application. This can be simplified down to 5 lines in total; two import lines, two controller lines, and one line to serve it. """ import logging from paste import httpserver from web.core import Application from web.rpc.amf import AMFController class TestService(AMFController): def hello(self, name="world"): return "Hello, %(name)s!" % dict(name=name) if __name__ == '__main__': logging.basicConfig(level=logging.INFO) app = Application.factory(root=TestService, debug=False) httpserver.serve(app, host='127.0.0.1', port='8080')
"""A basic hello world application. This can be simplified down to 5 lines in total; two import lines, two controller lines, and one line to serve it. """ import logging from paste import httpserver from web.core import Application from web.rpc.xml import XMLRPCController class TestService(XMLRPCController): def hello(self, name="world"): return "Hello, %(name)s!" % dict(name=name) class RootController(XMLRPCController): test = TestService() if __name__ == '__main__': logging.basicConfig(level=logging.INFO) app = Application.factory(root=RootController) httpserver.serve(app, host='127.0.0.1', port='8080')
from web.ext.annotation import AnnotationExtension # Built-in to WebCore. from web.ext.debug import DebugExtension from web.ext.serialize import SerializationExtension # New in 2.0.3! from web.ext.db import DatabaseExtension # From external dependency: web.db # Get a reference to our database connection adapter. from web.db.mongo import MongoDBConnection # From extenral dependency: marrow.mongo # Get a reference to our Wiki root object. from web.app.wiki.root import Wiki # This is our WSGI application instance. app = Application( Wiki, extensions=[ # Extensions that are always enabled. AnnotationExtension( ), # Allows us to use Python 3 function annotations. SerializationExtension( ), # Allows the return of mappings from endpoints, transformed to JSON. DatabaseExtension(MongoDBConnection("mongodb://localhost/test")), ] + ([ # Extensions that are only enabled in development or testing environments. DebugExtension( ) # Interactive traceback debugger, but gives remote code execution access. ] if __debug__ else [])) # If we're run as the "main script", serve our application over HTTP. if __name__ == "__main__": app.serve('wsgiref')
parts.append(executor.submit(mul, i, j)) def stream(parts, timeout=None): try: for future in as_completed(parts, timeout): mime, result = future.result() result = result.encode('utf8') yield "!!!!!!=_NextPart_{num}\nContent-Type: {mime}\nContent-Length: {length}\n\n".format( num = randint(100000000, 999999999), mime = mime, length = len(result) ).encode('utf8') + result except TimeoutError: for future in parts: future.cancel() response.content_length = None response.app_iter = stream(parts, 0.2) return response if __name__ == '__main__': from web.core import Application # wsgiref streams the chunks correctly, waitress buffers in 18000 byte chunks. Application(root, logging={'level': 'debug'}).serve('waitress', send_bytes=1)
#!/usr/bin/env python # encoding: utf-8 """A basic hello world application. This can be simplified down to 5 lines in total; two import lines, two controller lines, and one line to serve it. """ from web.core import Controller class RootController(Controller): def index(self): return 'Hello world!' if __name__ == '__main__': import logging from paste import httpserver from web.core import Application logging.basicConfig(level=logging.INFO) app = Application.factory(root=RootController, debug=True, **{'web.static': True, 'web.static.root': '/static'}) httpserver.serve(app, host='127.0.0.1', port='8080')
class TestService(AMFController): def hello(self, name="world"): return "Hello, %(name)s!" % dict(name=name) class RootController(AMFController): test = TestService() if __name__ == '__main__': import logging from paste import httpserver from web.core import Application logging.basicConfig(level=logging.INFO) app = Application.factory(root=RootController, debug=False, **{ 'web.sessions': False, 'web.widgets': False, 'web.beaker': False, 'web.profile': False, 'web.static': False, 'web.compress': False }) httpserver.serve(app, host='127.0.0.1', port='8080')
value = String(default=None) class Root(object): def __init__(self, context): self._ctx = context def get(self): return repr(self._ctx.session.__data__) def set(self, value): self._ctx.session.value = value return "OK" app = Application( Root, extensions=[ DebugExtension(), DatabaseExtension( session=MongoDBConnection('mongodb://localhost/test')), SessionExtension( secret='xyzzy', expires=24 * 90, default=MongoSession(Session, database='session'), ), ]) if __name__ == "__main__": app.serve('wsgiref', host='0.0.0.0', port=8080)
def test_autostatic(self): Application.factory(root=RootController, **{'web.static': True})
import time import pytest from webob import Request from web.core import Application from web.core.context import Context from web.ext.analytics import AnalyticsExtension def endpoint(context): time.sleep(0.1) return "Hi." sample = Application(endpoint, extensions=[AnalyticsExtension()]) def test_analytics_extension(): ctx = Context(response=Context(headers=dict())) ext = AnalyticsExtension() assert not hasattr(ctx, '_start_time') ext.prepare(ctx) assert hasattr(ctx, '_start_time') ext.before(ctx) time.sleep(0.1) ext.after(ctx) assert 0.1 <= float(ctx.response.headers['X-Generation-Time']) <= 0.2
# encoding: utf-8 """Exception handling test application. This application always raises 404 Not Found. """ from webob.exc import HTTPNotFound def exception(context): raise HTTPNotFound() if __name__ == '__main__': from web.core import Application Application(exception).serve('wsgiref')
def test_dotload(self): self.assertRaises(TypeError, lambda: Application.factory(root='web.core.application:Application', **test_config))
#!/usr/bin/env python # encoding: utf-8 """A basic hello world application. This can be simplified down to 5 lines in total; two import lines, two controller lines, and one line to serve it. """ import logging from paste import httpserver from web.core import Application from web.rpc.xml import XMLRPCController class TestService(XMLRPCController): def hello(self, name="world"): return "Hello, %(name)s!" % dict(name=name) if __name__ == '__main__': logging.basicConfig(level=logging.INFO) app = Application.factory(root=TestService) httpserver.serve(app, host='127.0.0.1', port='8080')
def test_enforceroot(self): self.assertRaises(ValueError, lambda: Application.factory(root=dict()))
# encoding: utf-8 """A one-function WebCore 2 demonstration application. Applications can be as simple or as complex and layered as your needs dictate. """ def basic(context, name="world"): 1 / 0 return "Hello {name}.".format(name=name) if __name__ == '__main__': from web.core import Application from web.ext.debug import DebugExtension Application(basic, extensions=[DebugExtension()]).serve('waitress')