本文整理汇总了Python中pyramid.threadlocal.get_current_request函数的典型用法代码示例。如果您正苦于以下问题:Python get_current_request函数的具体用法?Python get_current_request怎么用?Python get_current_request使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_current_request函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_verify_login_record_is_updated
def test_verify_login_record_is_updated():
# Use a fake session for this test.
user_id = db_utils.create_user()
sess = get_current_request().weasyl_session = create_session(user_id)
db = d.connect()
db.add(sess)
db.flush()
d.engine.execute("UPDATE login SET last_login = -1 WHERE userid = %(id)s", id=user_id)
login.signin(get_current_request(), user_id)
last_login = d.engine.scalar("SELECT last_login FROM login WHERE userid = %(id)s", id=user_id)
assert last_login > -1
示例2: linkFrom
def linkFrom(validator, linkFrom, instance, schema):
# avoid circular import
from contentbase import Item, TYPES
linkType, linkProp = linkFrom.split('.')
if validator.is_type(instance, "string"):
request = get_current_request()
base = request.root.by_item_type[linkType]
try:
item = find_resource(base, instance.replace(':', '%3A'))
if item is None:
raise KeyError()
except KeyError:
error = "%r not found" % instance
yield ValidationError(error)
return
if not isinstance(item, Item):
error = "%r is not a linkable resource" % instance
yield ValidationError(error)
return
if linkType not in set([item.item_type] + item.base_types):
error = "%r is not of type %s" % (instance, repr(linkType))
yield ValidationError(error)
return
pass
else:
path = instance.get('@id')
request = get_current_request()
if validator._serialize:
lv = len(validator._validated)
if '@id' in instance:
del instance['@id']
# treat the link property as not required
# because it will be filled in when the child is created/updated
subschema = request.registry[TYPES][linkType].schema
subschema = copy.deepcopy(subschema)
if linkProp in subschema['required']:
subschema['required'].remove(linkProp)
for error in validator.descend(instance, subschema):
yield error
if validator._serialize:
validated_instance = validator._validated[lv]
del validator._validated[lv:]
if path is not None:
item = find_resource(request.root, path.replace(':', '%3A'))
validated_instance['uuid'] = str(item.uuid)
elif 'uuid' in validated_instance: # where does this come from?
del validated_instance['uuid']
validator._validated[-1] = validated_instance
示例3: task_prerun_signal
def task_prerun_signal(task_id, task, args, kwargs, **kwaargs):
if hasattr(celery, "pyramid"):
env = celery.pyramid
env = prepare(registry=env["request"].registry)
proper_base_url = env["request"].registry.settings["base_url"]
tmp_request = Request.blank("/", base_url=proper_base_url)
# ensure tasks generate url for right domain from config
env["request"].environ["HTTP_HOST"] = tmp_request.environ["HTTP_HOST"]
env["request"].environ["SERVER_PORT"] = tmp_request.environ["SERVER_PORT"]
env["request"].environ["SERVER_NAME"] = tmp_request.environ["SERVER_NAME"]
env["request"].environ["wsgi.url_scheme"] = tmp_request.environ[
"wsgi.url_scheme"
]
get_current_request().tm.begin()
示例4: push
def push(self, message):
collection = get_current_request().db[self.__collection__]
now = datetime.datetime.utcnow()
message['created'] = now
request = get_current_request()
for _id in self.shared_by:
if request.user._id != _id:
other_id = _id
collection.update({'_id': self._id, 'user_data._id': other_id},
{'$push': {'messages': message},
'$set': {'date_modified': now },
'$inc': {'user_data.$.new' : 1},
})
示例5: test_start_scheduler
def test_start_scheduler(mock):
from papaye.config.startup import start_scheduler
from papaye.config.utils import SettingsReader
config = Configurator()
config.registry.settings = {
'papaye.cache': 'true',
'papaye.scheduler': 'papaye.tests.test_config:SchedulerTest',
}
config.add_directive('settings_reader', lambda c: SettingsReader(c))
start_scheduler(config)
get_current_request()
assert isinstance(mock.call_args[0][0], SchedulerTest)
示例6: test_start_scheduler_without_cache_in_configuration
def test_start_scheduler_without_cache_in_configuration(mock):
from papaye.config.startup import start_scheduler
from papaye.tasks.devices import DummyScheduler
from papaye.config.utils import SettingsReader
config = Configurator()
config.registry.settings = {
'papaye.cache': 'true',
}
config.add_directive('settings_reader', lambda c: SettingsReader(c))
start_scheduler(config)
get_current_request()
assert isinstance(mock.call_args[0][0], DummyScheduler)
示例7: timestruct
def timestruct(jinja_ctx, context, **kw):
"""Render both humanized time and accurate time.
* show_timezone
* target_timezone
* source_timezone
* format
"""
if not context:
return ""
assert type(context) in (datetime.datetime, datetime.time,)
request = jinja_ctx.get('request') or get_current_request()
if not jinja_ctx:
return ""
kw = kw.copy()
kw["time"] = context
kw["format"] = kw.get("format") or "YYYY-MM-DD HH:mm"
return Markup(render("core/timestruct.html", kw, request=request))
示例8: resolve_next_date
def resolve_next_date(self, args, info):
"""Return first date in the start_end interval.
"""
request = get_current_request()
start, end = getattr(request, 'start_end', (None, None))
dates = occurences_start(self._root, 'dates', from_=start, until=end)
return dates[0].date() if dates else None
示例9: add_renderer_globals
def add_renderer_globals(event):
""" add globals to templates
csrf_token - bare token
csrf_token_field - hidden input field with token inserted
flash - flash messages
"""
request = event.get('request')
settings = get_current_registry().settings
template = settings['apex.apex_render_template']
if request is None:
request = get_current_request()
csrf_token = request.session.get_csrf_token()
globs = {
'csrf_token': csrf_token,
'csrf_token_field': '<input type="hidden" name="csrf_token" value="%s" />' % csrf_token,
'flash': flash,
}
if template.endswith('.pt'):
globs['flash_t'] = get_renderer('apex:templates/flash_template.pt').implementation()
event.update(globs)
示例10: get_url
def get_url(self, namespace, key, seconds=3600, https=False):
"""Returns a Pyramid static URL.
If you use another web framework, please override this method.
"""
from pyramid.threadlocal import get_current_request
return get_current_request().static_url("/".join((self.storage_path, str(namespace), key)))
示例11: beforerender_subscriber
def beforerender_subscriber(event):
request = event['request']
if request is None:
request = get_current_request()
if getattr(request, 'debug_toolbar', None) is not None:
for panel in request.debug_toolbar.panels:
panel.process_beforerender(event)
示例12: after_request
def after_request(response):
if flask.request.method == 'OPTIONS':
in_value = response.headers.get('Access-Control-Allow-Headers', '')
allowed = [h.strip() for h in in_value.split(',')]
allowed.append('X-Client-ID')
out_value = ', '.join(allowed)
response.headers['Access-Control-Allow-Headers'] = out_value
return response
if 200 <= response.status_code < 300:
match = re.match(r'^store\.(\w+)_annotation$', flask.request.endpoint)
if match:
request = get_current_request()
action = match.group(1)
if action == 'delete':
data = json.loads(flask.request.data)
else:
data = json.loads(response.data)
annotation = wrap_annotation(data)
event = events.AnnotationEvent(request, annotation, action)
request.registry.notify(event)
return response
示例13: indirect_idea_content_links
def indirect_idea_content_links(self):
from pyramid.threadlocal import get_current_request
request = get_current_request()
if request:
return self.indirect_idea_content_links_with_cache()
else:
return self.indirect_idea_content_links_without_cache()
示例14: before_request
def before_request():
request = get_current_request()
annotation_ctor = request.registry.getUtility(interfaces.IAnnotationClass)
flask.g.annotation_class = annotation_ctor
flask.g.auth = Authenticator(request)
flask.g.authorize = functools.partial(authorize, request)
flask.g.before_annotation_update = anonymize_deletes
示例15: user_tagged_content
def user_tagged_content(event):
if ITagAddedEvent.providedBy(event):
request = get_current_request()
context = getattr(request, "context", None)
if context is None:
return
events = find_events(context)
if not events:
return
site = find_site(context)
catalog = find_catalog(context)
path = catalog.document_map.address_for_docid(event.item)
tagged = find_resource(site, path)
if tagged is None:
return
profile_id = event.user
if profile_id in (None, "None"):
return
profile = site["profiles"][profile_id]
info = _getInfo(profile, tagged)
if info is None:
return
if info["content_type"] == "Community":
info["flavor"] = "tagged_community"
elif info["content_type"] == "Person":
info["flavor"] = "tagged_profile"
else:
info["flavor"] = "tagged_other"
info["operation"] = "tagged"
info["tagname"] = event.name
events.push(**info)