本文整理汇总了Python中routes.Mapper类的典型用法代码示例。如果您正苦于以下问题:Python Mapper类的具体用法?Python Mapper怎么用?Python Mapper使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Mapper类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: __init__
class RouterApp:
""" Route request to the matching wsgiapp. """
def __init__(self,mode):
self.map = Mapper()
self.__routing_table = {}; # Maps path to app.
self.mode = mode
# HTTP POST json
# -> webob (maybe no need?)
def __call__(self, environ, start_response):
req = Request(environ);
# print 'env:\n', environ
# print 'route:\n', req.path_qs
# print 'match:\n', self.map.match(req.path_qs)
match = self.map.match(req.path_qs)
if match:
m = match['middleware']
h = match['handler']
o = self.__routing_table[m]
if o is not None:
environ['_HANDLER'] = h
return o(environ, start_response)
err = exc.HTTPNotFound('NO SERVICE FOUND')
return err(environ, start_response)
def add_route(self, pat, mid, han):
if mid not in self.__routing_table: # middleware being SINGELTON
self.__routing_table[mid] = \
middleware_factory(mid,self.mode);
self.map.connect(pat,middleware=mid,handler=han)
开发者ID:taggit,项目名称:taggit.cc,代码行数:31,代码来源:ps_router.py
示例2: make_map
def make_map(config):
"""Create, configure and return the routes Mapper"""
mapper = Mapper()
connect = mapper.connect
# For backwards compatibility with 0.9.7.
mapper.explicit = False
# Note that all of this are relative to the base path, /api.
if 'pycloud.api.encrypted' in config and config['pycloud.api.encrypted'] == 'true':
connect('command', '/command', controller='encrypted', action='command')
else:
# Service commands.
connect('list', '/services', controller='services', action='list')
connect('find', '/services/get', controller='services', action='find')
# SVM commands.
connect('startvm', '/servicevm/start', controller='servicevm', action='start')
connect('stopvm', '/servicevm/stop', controller='servicevm', action='stop')
# Appcommands.
connect('getAppList', '/apps', controller='apppush', action='getList')
connect('getApp', '/apps/get', controller='apppush', action='getApp')
# Metadata commands.
connect('metadata', '/system', controller='cloudlet', action='metadata')
return mapper
开发者ID:mkuai,项目名称:pycloud,代码行数:29,代码来源:routing.py
示例3: App
class App(object):
def __init__(self):
print "step in App.__init__()..."
self.myjob = MyJob()
self.m = Mapper()
self.m.connect('/myjob/{action}/{id}', controller=MyJob)
self.router = middleware.RoutesMiddleware(self.dispatch, self.m)
@wsgify
def dispatch(self, req):
print "step in App.dispatch()..."
match = req.environ['wsgiorg.routing_args'][1]
#print "wsgiorg.routing_args|match: %s\r\n%s\r\n" % (match,req.environ['wsgiorg.routing_args'])
if not match:
return 'error url: %s\r\n' % req.environ['PATH_INFO']
action = match['action']
if hasattr(self.myjob, action):
func = getattr(self.myjob, action)
ret = func()
return ret
else:
return "has no action:%s in %s \r\n" % (action, controller)
@wsgify
def __call__(self, req):
print "step in __call__()"
return self.router
开发者ID:aishi1979,项目名称:myCode,代码行数:30,代码来源:allInOne.py
示例4: get_map
def get_map():
" This function returns mapper object for dispatcher "
map = Mapper()
# Add routes here
urlmap(map, [
('/', 'controllers#index'),
('/write', 'controllers#write'),
('/read', 'controllers#read'),
('/clean', 'controllers#clean'),
('/reset', 'controllers#reset')
])
# Old style map connecting
#map.connect('Route_name', '/route/url', controller='controllerName',
#action='actionName')
if DEBUG:
r = [Route(None, '/{path_info:.*}',
controller='noodles.utils.static',
action='index',
path=os.path.join(os.getcwd(), 'static'),
auth=True)]
map.extend(r, '/static')
return map
开发者ID:SandStormHoldings,项目名称:NoodlesFramework,代码行数:26,代码来源:urls.py
示例5: make_app
def make_app(self, req):
map = Mapper()
map.connect("index", "/", method="index")
results = map.routematch(environ=req.environ)
if results:
match, route = results
req.urlvars = ((), match)
kwargs = match.copy()
method = kwargs.pop("method")
return getattr(self, method)(req, **kwargs)
else:
public_path = os.path.join(os.path.dirname(__file__), "public")
if not os.path.exists(public_path):
return exc.HTTPNotFound()
path = req.path
if path.startswith("/"):
path = path[1:]
public_file_path = os.path.join(public_path, path)
if os.path.exists(public_file_path):
if path.endswith(".css"):
req.response.content_type = "text/css"
elif path.endswith(".js"):
req.response.content_type = "text/javascript"
return open(public_file_path, "r").read().strip()
else:
return exc.HTTPNotFound()
开发者ID:jocelynj,项目名称:weboob,代码行数:27,代码来源:videoob_web.py
示例6: test_redirect_middleware
def test_redirect_middleware():
map = Mapper(explicit=False)
map.minimization = True
map.connect('myapp/*path_info', controller='myapp')
map.redirect("faq/{section}", "/static/faq/{section}.html")
map.redirect("home/index", "/", _redirect_code='301 Moved Permanently')
map.create_regs(['content', 'myapp'])
app = TestApp(RoutesMiddleware(simple_app, map))
res = app.get('/')
assert 'matchdict items are []' in res
res = app.get('/faq/home')
eq_('302 Found', res.status)
eq_(res.headers['Location'], '/static/faq/home.html')
res = app.get('/myapp/some/other/url')
print res
assert b"matchdict items are [('action', " + repr(u'index').encode() + \
b"), ('controller', " + repr(u'myapp').encode() + \
b"), ('path_info', 'some/other/url')]" in res
assert "'SCRIPT_NAME': '/myapp'" in res
assert "'PATH_INFO': '/some/other/url'" in res
res = app.get('/home/index')
assert '301 Moved Permanently' in res.status
eq_(res.headers['Location'], '/')
开发者ID:JanKanis,项目名称:routes,代码行数:27,代码来源:test_middleware.py
示例7: API
class API(object):
"""Our REST API WSGI application."""
def __init__(self, log):
self.log = log
self.mapper = Mapper()
self.controllers = {}
self.mapper.collection("routes", "route",
path_prefix="/route", controller="route",
collection_actions=['index', 'create'],
member_actions=['show', 'delete'],
member_prefix="/{route}", formatted=False)
def add(self, name, controller):
self.controllers[name] = controller
def create_app(self):
return RoutesMiddleware(
self, self.mapper, use_method_override=False, singleton=False)
@wsgify
def __call__(self, request):
# handle incoming call. depends on the routes middleware.
url, match = request.environ['wsgiorg.routing_args']
if match is None or 'controller' not in match:
raise HTTPNotFound()
resource = self.controllers[match.pop('controller')]
action = match.pop('action')
return getattr(resource, action)(request, url, **match)
开发者ID:leochencipher,项目名称:router,代码行数:30,代码来源:api.py
示例8: __new__
def __new__(cls, name, bases, dct):
result = type.__new__(cls, name, bases, dct)
if type(bases[0]) == type:
return result
if not hasattr(result, 'mapping'):
raise TypeError('Route application without mapping.')
from routes import Mapper
mapper = Mapper()
controllers = {}
controller_map = {}
for m in result.mapping:
name = m[0].split('/', 1)[0]
internal = str(id(m[1]))
controllers[internal] = m[1]
controller_map[m[1]] = internal
kwargs = {}
if len(m) >= 3 and not m[2] is None:
kwargs['requirements'] = m[2]
if len(m) == 4:
kwargs.update(m[3])
mapper.connect(name, m[0], controller=internal, **kwargs)
mapper.create_regs(controllers.keys())
result._routes_mapper = mapper
result._routes_controllers = controllers
result._controller_map = controller_map
return result
开发者ID:statico,项目名称:friend-rescue,代码行数:26,代码来源:application.py
示例9: Route
class Route(object):
def __init__(self):
self.map = Mapper()
self.map.resource("server", "servers",
controller="services",
collection={'detail': 'GET'},
member={'action': 'POST'})
开发者ID:windskyer,项目名称:mvpn,代码行数:7,代码来源:cc.py
示例10: testManyPages
def testManyPages():
"""
Test: Tries to fit 100 items on 15-item pages
"""
from routes import Mapper
items = range(100)
# Create routes mapper so that webhelper can create URLs
# using routes.url_for()
map = Mapper()
map.connect(':controller')
page = Page(items, current_page=0, items_per_page=15)
assert page.current_page==1
assert page.first_item==0
assert page.last_item==14
assert page.first_page==1
assert page.last_page==7
assert page.items_per_page==15
assert page.item_count==100
assert page.page_count==7
# Test deprecated navigator()
assert page.navigator()=='[<strong>1</strong>] <a href="/content?page_nr=2">2</a> <a href="/content?page_nr=3">3</a> .. <a href="/content?page_nr=7">7</a>'
assert page.pager()=='<span class="pager_curpage">1</span> <a href="/content?page_nr=2" class="pager_link">2</a> <a href="/content?page_nr=3" class="pager_link">3</a> <span class="pager_dotdot">..</span> <a href="/content?page_nr=7" class="pager_link">7</a>'
assert page.pager(separator='_')=='<span class="pager_curpage">1</span>_<a href="/content?page_nr=2" class="pager_link">2</a>_<a href="/content?page_nr=3" class="pager_link">3</a>_<span class="pager_dotdot">..</span>_<a href="/content?page_nr=7" class="pager_link">7</a>'
assert page.pager(link_var='xy')=='<span class="pager_curpage">1</span> <a href="/content?xy=2" class="pager_link">2</a> <a href="/content?xy=3" class="pager_link">3</a> <span class="pager_dotdot">..</span> <a href="/content?xy=7" class="pager_link">7</a>'
assert page.pager(link_attr={'style':'s1'},curpage_attr={'style':'s2'},dotdot_attr={'style':'s3'})=='<span style="s2">1</span> <a href="/content?page_nr=2" style="s1">2</a> <a href="/content?page_nr=3" style="s1">3</a> <span style="s3">..</span> <a href="/content?page_nr=7" style="s1">7</a>'
开发者ID:pawelniewie,项目名称:5groszy.pl,代码行数:26,代码来源:__init__.py
示例11: setup_routes
def setup_routes(self):
map = Mapper(directory=config['pylons.paths']['controllers'],
always_scan=config['debug'])
# Setup a default route for the root of object dispatch
map.connect('*url', controller=self.root_controller,
action='routes_placeholder')
config['routes.map'] = map
开发者ID:Bitergia,项目名称:allura,代码行数:7,代码来源:app_cfg.py
示例12: make_map
def make_map(config):
"""Create, configure and return the routes Mapper"""
map = Mapper(directory=config['pylons.paths']['controllers'],
always_scan=config['debug'])
map.minimization = False
map.explicit = False
mc = map.connect
# The ErrorController route (handles 404/500 error pages); it should
# likely stay at the top, ensuring it can always be resolved
mc('/error/{action}', controller='error')
mc('/error/{action}/{id}', controller='error')
# Home
mc('/', controller='home', action='index')
# very custom
mc('/{id}-{title}', controller='page', action='view')
mc('/cms', controller='mgmt', action='index')
mc('/cms/{action}', controller='mgmt')
mc('/cms/{action}/{id}', controller='mgmt')
mc('/nieuws', controller='news', action='list')
mc('/nieuws/{id}/{title}', controller='news', action='view')
mc('/resource/{action}/{id}/{name}', controller='fetch')
# Default fallbacks (cms, other pages)
mc('/{controller}', action='index')
mc('/{controller}/{action}')
mc('/{controller}/{action}/{id}')
return map
开发者ID:geonetix,项目名称:eencms,代码行数:35,代码来源:routing.py
示例13: Application
class Application(object):
def __init__(self):
self.map = Mapper()
self.map.connect('app1', '/app1url', app=app1)
self.map.connect('app2', '/app2url', app=app2)
def __call__(self, environ, start_response):
match = self.map.routematch(environ=environ)
if not match:
return self.error404(environ, start_response)
return match[0]['app'](environ, start_response)
def error404(self, environ, start_response):
html = b"""\
<html>
<head>
<title>404 - Not Found</title>
</head>
<body>
<h1>404 - Not Found</h1>
</body>
</html>
"""
headers = [
('Content-Type', 'text/html'),
('Content-Length', str(len(html)))
]
start_response('404 Not Found', headers)
return [html]
开发者ID:1stvamp,项目名称:gunicorn,代码行数:29,代码来源:multiapp.py
示例14: __init__
def __init__(self):
a = Controller()
_map = Mapper()
"""路由匹配条件1"""
# map.connect('/images',controller=a,
# action='search',
# conditions={'method':['GET']})
"""路由匹配条件2"""
# map.connect('name',"/{action}/{pid}",controller=a)
"""路由匹配条件3"""
# map.resource("message","messages",controller=a,collection={'search':'GET'})
"""路由匹配条件4"""
# map.resource('message', 'messages',controller=a,
# collection={'list_many':'GET','create_many':'POST'},
# member={'update_many':'POST','delete_many':'POST'})
"""路由匹配条件5"""
_map.resource('message', 'messages', controller=a, path_prefix='/{projectid}',
collection={'list_many': 'GET', 'create_many': 'POST'},
member={'update_many': 'POST', 'delete_many': 'POST'})
# _map.resource('type', 'types', controller=other_controller,
# parent_resource=dict(member_name='message',
# collection_name='messages'),
# path_prefix='{projectid}/%s/:%s_id' % ('nex', 'nexs'))
self.route = middleware.RoutesMiddleware(self._dispatch, _map)
开发者ID:usernameisnull,项目名称:cinder-explanation,代码行数:26,代码来源:bbbb.py
示例15: __init__
def __init__(self, *args, **kw):
super(RoutedController, self).__init__(*args, **kw)
routes = []
for name in dir(self):
value = getattr(self.__class__, name, None)
if value is None:
continue
deco = None
if inspect.ismethod(value): # pragma: no cover
# PY2
deco = Decoration.get_decoration(value.__func__)
elif inspect.isfunction(value): # pragma: no cover
# PY3
deco = Decoration.get_decoration(value)
if deco is None:
continue
if hasattr(deco, '_tgext_routes'):
routes.extend(deco._tgext_routes)
if routes:
instance_mapper = Mapper()
if self.mapper is not None:
instance_mapper.extend(self.mapper.matchlist)
instance_mapper.extend(routes)
self.mapper = instance_mapper
开发者ID:TurboGears,项目名称:tgext.routes,代码行数:29,代码来源:dispatch.py
示例16: BaseApplication
class BaseApplication(object):
special_vars = ['controller','action']
def __init__(self, conf):
self.mapper = Mapper()
self.mapper.connect('/test',controller = TestController,
conditions = dict(method=['PUT']))
self.mapper.connect('/test',controller = TestController,
conditions = dict(method=['GET']))
def __call__(self, env, start_response):
req = Request(env)
return self.handle_request(req)(env, start_response)
def handle_request(self, req):
print 'into mapping'
results = self.mapper.routematch(environ=req.environ)
print 'results --- after mapping'
print '---- show result -----'
print results
match, route = results
controller = match['controller'](self)
try:
handler = getattr(controller, req.method)
except AttributeError:
return HTTPMethodNotAllowed(request = req)
#getattr(handler, 'publicly_accessible')
kwargs = match.copy()
for attr in self.special_vars:
if attr in kwargs:
del kwargs[attr]
#return handler(req, **kwargs)
return handler(req, **kwargs)
开发者ID:jonahwu,项目名称:lab,代码行数:33,代码来源:myapp.py
示例17: MyResourceRouter
class MyResourceRouter(object):
def __init__(self):
route_name = 'resource'
route_path = 'resor'
my_application = Application(TestAction())
self.mapper = Mapper()
self.mapper.resource(route_name, route_path, controller=my_application)
self.mapper.connect('resconnct', '/getkey',
controller=my_application,
action='getkey',
conditions={'method':['GET']})
self._router = routes.middleware.RoutesMiddleware(self._dispatch, self.mapper)
@webob.dec.wsgify(RequestClass=webob.Request)
def __call__(self, req):
print 'MyRouter is invoked'
return self._router
@staticmethod
@webob.dec.wsgify(RequestClass=webob.Request)
def _dispatch(req):
print 'RoutesMiddleware is invoked, calling the dispatch back'
match_dict = req.environ['wsgiorg.routing_args'][1]
if not match_dict:
return webob.exc.HTTPNotFound()
app = match_dict['controller']
return app
开发者ID:fengkaicnic,项目名称:routes-test,代码行数:33,代码来源:router.py
示例18: URLMapper
class URLMapper():
""" Unlike the normal routes.Mapper, URLMapper works on urls with scheme, etc...
Except, right now it doesn't really; eventually, make this match stuff """
def __init__(self):
self.mapper = Mapper()
self._add_routes()
def _add_routes(self):
""" override this in the subclass to add routes at create-time """
pass
def make_path_with_query(self, parsed):
if parsed.query:
return parsed.path + '/' + parsed.query
return parsed.path
def match(self, uri):
parsed = urlsplit(uri, 'http')
path = self.make_path_with_query(parsed)
if not path:
return None
return self.mapper.match(path)
def connect(self, *args, **kwargs):
#domain = kwargs.get('domain', '_default')
return self.mapper.connect(*args, **kwargs)
开发者ID:antiface,项目名称:python-crawler,代码行数:28,代码来源:map.py
示例19: __init__
def __init__(self):
print '__init__'
self.controller = Test()
mapper = Mapper()
mapper.connect('blog', '/blog/{action}/{id}', controller=Test,conditions={'method': ['GET']})
mapper.redirect('/', '/blog/index/1')
self.router = middleware.RoutesMiddleware(self.dispatch, mapper)
开发者ID:fjrti,项目名称:snippets,代码行数:7,代码来源:xxx.py
示例20: SensorHandler
class SensorHandler(tornado.web.RequestHandler):
"""Uses an aysnchronous call to an RPC server to calculate fib(x).
As with examples of asynchronous HTTP calls, this request will not finish
until the remote response is received."""
def initialize(self,database):
self.mapper=Mapper()
self.mapper.connect(None,"/{action}/{exchange}/{queue}")
self.mapper.connect(None,"/{action}/{exchange}/")
## need to know something about the exchanges and queues in the
## broker
#self.cl = Client('localhost:55672', 'guest', 'guest')
def post(self, number=''):
global cl
request = self.request
self.data = request.body
result = self.mapper.match(request.uri)
self.queue =''
try:
self.queue = result['queue']
except:
pass;
self.pika_client = self.application.settings.get('pika_client')
self.mq_ch = self.pika_client.channel
self.corr_id = str(uuid.uuid4())
self.exchange= result['exchange']
try:
pub=self.mq_ch.basic_publish(exchange=self.exchange, routing_key=self.queue,body=self.data)
response={"Response":"Message sent"}
self.write(json.dumps(response))
except:
response={"Reponse":"Error publishing msg to exchange"}
self.write(json.dumps(response))
开发者ID:aaravindanarun,项目名称:random_bits,代码行数:33,代码来源:front.py
注:本文中的routes.Mapper类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论