本文整理汇总了Python中pyramid.request.Request.method方法的典型用法代码示例。如果您正苦于以下问题:Python Request.method方法的具体用法?Python Request.method怎么用?Python Request.method使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyramid.request.Request
的用法示例。
在下文中一共展示了Request.method方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_create_update
# 需要导入模块: from pyramid.request import Request [as 别名]
# 或者: from pyramid.request.Request import method [as 别名]
def test_create_update(self):
from papyrus.protocol import Protocol
from pyramid.request import Request
from geojson import Feature, FeatureCollection
from shapely.geometry import Point
MappedClass = self._get_mapped_class()
# a mock session specific to this test
class MockSession(object):
def query(self, mapped_class):
return {'a': mapped_class(Feature(id='a')),
'b': mapped_class(Feature(id='b'))}
def flush(self):
pass
proto = Protocol(MockSession, MappedClass, 'geom')
# we need an actual Request object here, for body to do its job
request = Request({})
request.method = 'POST'
request.body = '{"type": "FeatureCollection", "features": [{"type": "Feature", "id": "a", "properties": {"text": "foo"}, "geometry": {"type": "Point", "coordinates": [45, 5]}}, {"type": "Feature", "id": "b", "properties": {"text": "bar"}, "geometry": {"type": "Point", "coordinates": [46, 6]}}]}'
features = proto.create(request)
self.assertTrue(isinstance(features, FeatureCollection))
self.assertEqual(len(features.features), 2)
self.assertEqual(features.features[0].id, 'a')
self.assertEqual(features.features[0].text, 'foo')
self.assertTrue(features.features[0].geom.shape.equals(Point(45, 5)))
self.assertEqual(features.features[1].id, 'b')
self.assertEqual(features.features[1].text, 'bar')
self.assertTrue(features.features[1].geom.shape.equals(Point(46, 6)))
示例2: test_items_delete
# 需要导入模块: from pyramid.request import Request [as 别名]
# 或者: from pyramid.request.Request import method [as 别名]
def test_items_delete(self):
"""
Test deleting an item.
"""
# first create an item
self._create_item_status()
payload = {"name": "Macbook Air", "type": "TRADE", "quantity": "1",
"price": "", "description": "Lightweight lappy.",
"reason": "", "is_draft": "y", "uuid": str(uuid.uuid4())}
request = Request({}, method='POST', body=json.dumps(payload))
request.registry = self.config.registry
response = items(request)
self.assertEqual(response.status_code, 200)
self.assertEqual(DBSession.query(Item).count(), 1)
# try retrieving the newly added item
item = DBSession.query(Item).first()
# now send a delete request
request.method = 'DELETE'
request.matchdict = {'id': item.id}
request.body = None
items(request)
self.assertEqual(response.status_code, 200)
self.assertEqual(DBSession.query(Item).count(), 0)
示例3: test_create
# 需要导入模块: from pyramid.request import Request [as 别名]
# 或者: from pyramid.request.Request import method [as 别名]
def test_create(self):
from papyrus.protocol import Protocol
from pyramid.request import Request
from pyramid.response import Response
engine = self._get_engine()
Session = self._get_session(engine)
MappedClass = self._get_mapped_class()
class MockSession(object):
def add(self, o):
Session.add(o)
def flush(self):
pass
# a before_update callback
def before_create(request, feature, obj):
if not hasattr(request, '_log'):
request._log = []
request._log.append(dict(feature=feature, obj=obj))
proto = Protocol(MockSession, MappedClass, "geom",
before_create=before_create)
# we need an actual Request object here, for body to do its job
request = Request({})
request.method = 'POST'
request.body = '{"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {"text": "foo"}, "geometry": {"type": "Point", "coordinates": [45, 5]}}, {"type": "Feature", "properties": {"text": "foo"}, "geometry": {"type": "Point", "coordinates": [45, 5]}}]}'
proto.create(request)
self.assertEqual(len(request.response_callbacks), 1)
self.assertEqual(len(Session.new), 2)
for obj in Session.new:
self.assertEqual(obj.text, 'foo')
self.assertEqual(obj.geom.shape.x, 45)
self.assertEqual(obj.geom.shape.y, 5)
Session.rollback()
# test before_create
self.assertTrue(hasattr(request, '_log'))
self.assertEqual(len(request._log), 2)
self.assertEqual(request._log[0]['feature'].properties['text'], 'foo')
self.assertEqual(request._log[0]['obj'], None)
self.assertEqual(request._log[1]['feature'].properties['text'], 'foo')
self.assertEqual(request._log[1]['obj'], None)
# test response status
response = Response(status_int=400)
request._process_response_callbacks(response)
self.assertEqual(response.status_int, 201)
示例4: test_items_put_failed
# 需要导入模块: from pyramid.request import Request [as 别名]
# 或者: from pyramid.request.Request import method [as 别名]
def test_items_put_failed(self):
"""
Test that updating non-existent item fails.
"""
payload = {"name": "Macbook Pro", "type": "SALE", "quantity": "5",
"price": "200.00", "description": "Lightweight lappy.",
"reason": "", "is_draft": "n", "id": 1}
request = Request({}, method='PUT', body=json.dumps(payload))
request.registry = self.config.registry
request.matchdict = {'id': 1}
request.method = 'PUT'
self.assertRaises(HTTPBadRequest, items, request)
self.assertEqual(DBSession.query(Item).count(), 0)
示例5: test_create_badrequest
# 需要导入模块: from pyramid.request import Request [as 别名]
# 或者: from pyramid.request.Request import method [as 别名]
def test_create_badrequest(self):
from papyrus.protocol import Protocol
from pyramid.request import Request
engine = self._get_engine()
Session = self._get_session(engine)
MappedClass = self._get_mapped_class()
proto = Protocol(Session, MappedClass, "geom")
# we need an actual Request object here, for body to do its job
request = Request({})
request.method = 'POST'
request.body = '{"type": "Feature", "properties": {"text": "foo"}, "geometry": {"type": "Point", "coordinates": [45, 5]}}'
response = proto.create(request)
self.assertEqual(response.status_int, 400)
示例6: test_update_forbidden
# 需要导入模块: from pyramid.request import Request [as 别名]
# 或者: from pyramid.request.Request import method [as 别名]
def test_update_forbidden(self):
from papyrus.protocol import Protocol
from pyramid.request import Request
engine = self._get_engine()
Session = self._get_session(engine)
MappedClass = self._get_mapped_class()
proto = Protocol(Session, MappedClass, "geom", readonly=True)
# we need an actual Request object here, for body to do its job
request = Request({})
request.method = 'PUT'
request.body = '{"type": "Feature", "id": 1, "properties": {"text": "foo"}, "geometry": {"type": "Point", "coordinates": [45, 5]}}'
response = proto.update(request, 1)
self.assertTrue(response.headers.get('Allow') == "GET, HEAD")
self.assertEqual(response.status_int, 405)
示例7: test_update_badrequest
# 需要导入模块: from pyramid.request import Request [as 别名]
# 或者: from pyramid.request.Request import method [as 别名]
def test_update_badrequest(self):
from papyrus.protocol import Protocol
from pyramid.request import Request
# a mock session specific to this test
class MockSession(object):
def query(self, mapped_class):
return {'a': {}}
proto = Protocol(MockSession, self._get_mapped_class(), "geom")
# we need an actual Request object here, for body to do its job
request = Request({})
request.method = 'PUT'
request.body = '{"type": "Point", "coordinates": [45, 5]}'
response = proto.update(request, 'a')
self.assertEqual(response.status_int, 400)
示例8: test_create_empty
# 需要导入模块: from pyramid.request import Request [as 别名]
# 或者: from pyramid.request.Request import method [as 别名]
def test_create_empty(self):
from papyrus.protocol import Protocol
from pyramid.request import Request
from pyramid.response import Response
engine = self._get_engine()
Session = self._get_session(engine)
MappedClass = self._get_mapped_class()
proto = Protocol(Session, MappedClass, "geom")
# we need an actual Request object here, for body to do its job
request = Request({})
request.method = 'POST'
request.body = '{"type": "FeatureCollection", "features": []}'
resp = proto.create(request)
self.assertEqual(resp, None)
示例9: test_update
# 需要导入模块: from pyramid.request import Request [as 别名]
# 或者: from pyramid.request.Request import method [as 别名]
def test_update(self):
from papyrus.protocol import Protocol
from geojson import Feature
from pyramid.request import Request
from pyramid.response import Response
from geoalchemy import WKBSpatialElement
MappedClass = self._get_mapped_class()
# a mock session specific to this test
class MockSession(object):
def query(self, mapped_class):
return {'a': MappedClass(Feature(id='a'))}
def flush(self):
pass
# a before_update callback
def before_update(request, feature, obj):
request._log = dict(feature=feature, obj=obj)
proto = Protocol(MockSession, MappedClass, "geom",
before_update=before_update)
# we need an actual Request object here, for body to do its job
request = Request({})
request.method = 'PUT'
request.body = '{"type": "Feature", "id": "a", "properties": {"text": "foo"}, "geometry": {"type": "Point", "coordinates": [45, 5]}}'
obj = proto.update(request, "a")
self.assertEqual(len(request.response_callbacks), 1)
self.assertTrue(isinstance(obj, MappedClass))
self.assertTrue(isinstance(obj.geom, WKBSpatialElement))
self.assertEqual(obj.text, "foo")
# test before_update
self.assertTrue(hasattr(request, '_log'))
self.assertEqual(request._log["feature"].id, 'a')
self.assertEqual(request._log["feature"].properties['text'], 'foo')
self.assertTrue(isinstance(request._log["obj"], MappedClass))
# test response status
response = Response(status_int=400)
request._process_response_callbacks(response)
self.assertEqual(response.status_int, 201)
示例10: test_update_notfound
# 需要导入模块: from pyramid.request import Request [as 别名]
# 或者: from pyramid.request.Request import method [as 别名]
def test_update_notfound(self):
from papyrus.protocol import Protocol
from pyramid.request import Request
engine = self._get_engine()
Session = self._get_session(engine)
MappedClass = self._get_mapped_class()
# a mock session specific to this test
class MockSession(object):
def query(self, mapped_class):
return {}
proto = Protocol(MockSession, MappedClass, "geom")
# we need an actual Request object here, for body to do its job
request = Request({})
request.method = 'PUT'
request.body = '{"type": "Feature", "id": 1, "properties": {"text": "foo"}, "geometry": {"type": "Point", "coordinates": [45, 5]}}'
response = proto.update(request, 1)
self.assertEqual(response.status_int, 404)
示例11: test_mapproxy
# 需要导入模块: from pyramid.request import Request [as 别名]
# 或者: from pyramid.request.Request import method [as 别名]
def test_mapproxy(self):
from pyramid.request import Request
from papyrus_mapproxy import (load_mapproxy_config, create_view_callable,
add_route)
mapproxy_config_file = self.config.get_settings().get('mapproxy.yaml')
mapproxy_config = load_mapproxy_config(mapproxy_config_file)
view = create_view_callable(mapproxy_config)
add_route(self.config, view)
context = DummyContext()
request = Request({'wsgi.url_scheme': 'http', 'SERVER_NAME': 'foo',
'SERVER_PORT': '80'})
request.method = 'GET'
response = view(context, request)
from pyramid.response import Response
self.assertTrue(isinstance(response, Response))
self.assertTrue('Welcome to MapProxy' in response.body)
示例12: test_items_put
# 需要导入模块: from pyramid.request import Request [as 别名]
# 或者: from pyramid.request.Request import method [as 别名]
def test_items_put(self):
"""
Test updating an item.
"""
self._create_item_status()
payload = {"name": "Macbook Air", "type": "TRADE", "quantity": "1",
"price": "", "description": "Lightweight lappy.",
"reason": "", "is_draft": "y", "uuid": str(uuid.uuid4())}
request = Request({}, method='POST', body=json.dumps(payload))
request.registry = self.config.registry
# make the request
items(request)
# try retrieving the newly added item
item = DBSession.query(Item).first()
self.failUnless(item)
payload = {"name": "Macbook Pro", "type": "SALE", "quantity": "5",
"price": "200.00", "description": "Lightweight lappy.",
"reason": "", "is_draft": "n", "id": item.id}
request.matchdict = {'id': item.id}
request.method = 'PUT'
request.body = json.dumps(payload)
# make the request again
response = items(request)
self.assertEqual(response.status_code, 200)
# reload item
item = DBSession.query(Item).filter_by(id=item.id).first()
self.assertEqual(item.name, payload['name'])
self.assertEqual(item.type, payload['type'])
self.assertEqual(item.quantity, int(payload['quantity']))
self.assertEqual(str(item.price), payload['price'])
self.assertEqual(item.status_id, self.draft_status.id)
示例13: sdi_mgmt_views
# 需要导入模块: from pyramid.request import Request [as 别名]
# 或者: from pyramid.request.Request import method [as 别名]
def sdi_mgmt_views(context, request, names=None):
if not hasattr(context, '__name__'):
# shortcut if the context doesn't have a name (usually happens if the
# context is an exception); we do this because mgmt_path uses Pyramid's
# resource_path_tuple, which wants every object in the lineage to have
# a __name__.
return []
registry = request.registry
introspector = registry.introspector
unordered = []
# create a dummy request signaling our intent
req = Request(request.environ.copy())
req.script_name = request.script_name
req.context = context
req.matched_route = request.matched_route
req.method = 'GET'
req.registry = request.registry
sro_enum = list(enumerate(providedBy(context).__sro__[:-1]))
for data in introspector.get_category('sdi views'):
related = data['related']
sdi_intr = data['introspectable']
tab_title = sdi_intr['tab_title']
tab_condition = sdi_intr['tab_condition']
tab_before = sdi_intr['tab_before']
tab_after = sdi_intr['tab_after']
def is_view(intr):
return intr.category_name == 'views'
for view_intr in filter(is_view, related):
# NB: in reality, the above loop will execute exactly once because
# each "sdi view" is associated with exactly one pyramid view
view_name = view_intr['name']
req.path_info = request.sdiapi.mgmt_path(context, view_name)
if names is not None and not view_name in names:
continue
# do a passable job at figuring out whether, if we visit the
# url implied by this view, we'll be permitted to view it and
# something reasonable will show up
intr_context = view_intr['context']
sro_index = MAX_ORDER
if intr_context is None:
intr_context = Interface
if IInterface.providedBy(intr_context):
if not intr_context.providedBy(context):
continue
for i, spec in sro_enum:
if spec is intr_context:
sro_index = i
break
elif isinstance(context, intr_context):
for i, spec in sro_enum:
if spec.implementedBy(intr_context):
sro_index = i
break
else: # pragma: no cover (coverage bug, this is reached)
continue
if tab_condition is not None and names is None:
if callable(tab_condition):
if not tab_condition(context, request):
continue
elif not tab_condition:
continue
derived = view_intr['derived_callable']
if hasattr(derived, '__predicated__'):
if not derived.__predicated__(context, req):
continue
if hasattr(derived, '__permitted__'):
if not derived.__permitted__(context, req):
continue
predicate_order = getattr(derived, '__order__', MAX_ORDER)
if view_name == request.view_name:
css_class = 'active'
else:
css_class = None
unordered.append(
{'view_name': view_name,
'tab_before':tab_before,
'tab_after':tab_after,
'title': tab_title or view_name.capitalize(),
'class': css_class,
'predicate_order':predicate_order,
'sro_index':sro_index,
'url': request.sdiapi.mgmt_path(
request.context, '@@%s' % view_name)
}
)
# De-duplicate the unordered list of tabs with the same view_name. Prefer
# the tab with the lowest (sro_index, predicate_order) tuple, because this
# is the view that's most likely to be executed when visited and we'd
# like to get its title right.
unordered.sort(key=lambda s: (s['sro_index'], s['predicate_order']))
deduplicated = []
view_names = {}
#.........这里部分代码省略.........
示例14: sdi_mgmt_views
# 需要导入模块: from pyramid.request import Request [as 别名]
# 或者: from pyramid.request.Request import method [as 别名]
def sdi_mgmt_views(request, context=None, names=None):
registry = request.registry
if context is None:
context = request.context
introspector = registry.introspector
L = []
# create a dummy request signaling our intent
req = Request(request.environ.copy())
req.script_name = request.script_name
req.context = context
req.matched_route = request.matched_route
req.method = 'GET'
req.registry = request.registry
for data in introspector.get_category('sdi views'):
related = data['related']
sdi_intr = data['introspectable']
tab_title = sdi_intr['tab_title']
tab_condition = sdi_intr['tab_condition']
def is_view(intr):
return intr.category_name == 'views'
for view_intr in filter(is_view, related):
# NB: in reality, the above loop will execute exactly once because
# each "sdi view" is associated with exactly one pyramid view
view_name = view_intr['name']
req.path_info = request.mgmt_path(context, view_name)
if names is not None and not view_name in names:
continue
# do a passable job at figuring out whether, if we visit the
# url implied by this view, we'll be permitted to view it and
# something reasonable will show up
intr_context = view_intr['context']
if IInterface.providedBy(intr_context):
if not intr_context.providedBy(context):
continue
elif intr_context and not isinstance(context, intr_context):
continue
if tab_condition is not None and names is None:
if tab_condition is False or not tab_condition(
context, request):
continue
derived = view_intr['derived_callable']
if hasattr(derived, '__predicated__'):
if not derived.__predicated__(context, req):
continue
if hasattr(derived, '__permitted__'):
if not derived.__permitted__(context, req):
continue
if view_name == request.view_name:
css_class = 'active'
else:
css_class = None
L.append({'view_name': view_name,
'title': tab_title or view_name.capitalize(),
'class': css_class,
'url': request.mgmt_path(request.context,
'@@%s' % view_name)
})
ordered = []
tab_order = request.registry.content.metadata(context, 'tab_order')
if tab_order is not None:
ordered_names_available = [ y for y in tab_order if y in
[ x['view_name'] for x in L ] ]
for ordered_name in ordered_names_available:
for view_data in L:
if view_data['view_name'] == ordered_name:
L.remove(view_data)
ordered.append(view_data)
return ordered + sorted(L, key=operator.itemgetter('title'))
示例15: get_mgmt_views
# 需要导入模块: from pyramid.request import Request [as 别名]
# 或者: from pyramid.request.Request import method [as 别名]
def get_mgmt_views(request, context=None, names=None):
registry = request.registry
if context is None:
context = request.context
introspector = registry.introspector
L = []
# create a dummy request signaling our intent
req = Request(request.environ.copy())
req.script_name = request.script_name
req.context = context
req.matched_route = request.matched_route
req.method = 'GET'
req.registry = request.registry
for data in introspector.get_category('sdi views'):
related = data['related']
sdi_intr = data['introspectable']
tab_title = sdi_intr['tab_title']
tab_condition = sdi_intr['tab_condition']
if tab_condition is not None and names is None:
if tab_condition is False or not tab_condition(request):
continue
for intr in related:
view_name = intr['name']
if names is not None and not view_name in names:
continue
if intr.category_name == 'views' and not view_name in L:
derived = intr['derived_callable']
# do a passable job at figuring out whether, if we visit the
# url implied by this view, we'll be permitted to view it and
# something reasonable will show up
if IInterface.providedBy(intr['context']):
if not intr['context'].providedBy(context):
continue
elif intr['context'] and not isinstance(
context, intr['context']):
continue
req.path_info = request.mgmt_path(context, view_name)
if hasattr(derived, '__predicated__'):
if not derived.__predicated__(context, req):
continue
if hasattr(derived, '__permitted__'):
if not derived.__permitted__(context, req):
continue
L.append(
{'view_name':view_name,
'tab_title':tab_title or view_name.capitalize()}
)
ordered = []
if hasattr(context, '__tab_order__'):
tab_order = context.__tab_order__
ordered_names_available = [ y for y in tab_order if y in
[ x['view_name'] for x in L ] ]
for ordered_name in ordered_names_available:
for view_data in L:
if view_data['view_name'] == ordered_name:
L.remove(view_data)
ordered.append(view_data)
return ordered + sorted(L, key=operator.itemgetter('tab_title'))