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 = {}
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')
# 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')
# 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')
# 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')
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
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'} } } )
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')
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 []), )
# 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)
def do(root, path_): app = Application(root) req = Request.blank(path_) return req.get_response(app)
# 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')
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)
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)
# 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')