本文整理汇总了Python中trac.web.api.Request类的典型用法代码示例。如果您正苦于以下问题:Python Request类的具体用法?Python Request怎么用?Python Request使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Request类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: dummy_request
def dummy_request(env, uname=None):
environ = {}
setup_testing_defaults(environ)
environ.update({
'REQUEST_METHOD' : 'GET',
'SCRIPT_NAME' : urlparse(str(env._abs_href())).path,
'trac.base_url' : str(env._abs_href()),
})
req = Request(environ, lambda *args, **kwds: None)
# Intercept redirection
req.redirect = lambda *args, **kwds: None
# Setup user information
if uname is not None :
environ['REMOTE_USER'] = req.authname = uname
rd = RequestDispatcher(env)
chrome = Chrome(env)
req.callbacks.update({
'authname': rd.authenticate,
'chrome': chrome.prepare_request,
'hdf': getattr(rd, '_get_hdf', None),
'lc_time': rd._get_lc_time,
'locale' : getattr(rd, '_get_locale', None),
'perm': rd._get_perm,
'session': rd._get_session,
'tz': rd._get_timezone,
'form_token': rd._get_form_token
})
return req
示例2: dummy_request
def dummy_request(env, cookies_from=None, query=None):
environ = {
'trac.base_url': env.base_url,
'wsgi.url_scheme': 'http',
'wsgi.input': BytesIO(),
'SCRIPT_NAME': '/trac.cgi',
'REQUEST_METHOD': 'GET',
'SERVER_NAME': 'example.org',
'SERVER_PORT': '80',
'HTTP_HOST': 'example.org',
}
if query:
environ['QUERY_STRING'] = urlencode(query)
if cookies_from:
outcookie = cookies_from.outcookie
cookie = '; '.join('%s=%s' % (name, morsel.value)
for name, morsel in outcookie.items())
environ['HTTP_COOKIE'] = cookie
start_response = mock.Mock(name='start_response')
req = Request(environ, start_response)
req.session = {}
req.chrome = {'warnings': [], 'notices': []}
req.redirect = mock.Mock(name='req.redirect', spec=())
req.authname = 'anonymous'
return req
示例3: _test_import
def _test_import(self, env, filename, sheet = 1):
req = Request({'SERVER_PORT': 0, 'SERVER_NAME': 'any', 'wsgi.url_scheme': 'any', 'wsgi.input': 'any', 'REQUEST_METHOD': 'GET' }, lambda x, y: _printme)
try:
from trac.test import MockPerm
req.perm = MockPerm()
except ImportError:
pass
req.authname = 'testuser'
req.hdf = HDFWrapper([]) # replace by this if you want to generate HTML: req.hdf = HDFWrapper(loadpaths=chrome.get_all_templates_dirs())
db = env.get_db_cnx()
cursor = db.cursor()
_exec(cursor, "select * from enum")
enums_before = cursor.fetchall()
_exec(cursor, "select * from component")
components_before = cursor.fetchall()
#print enums_before
# when testing, always use the same time so that the results are comparable
#print "importing " + filename + " with tickettime " + str(ImporterTestCase.TICKET_TIME)
template, content_type = ImportModule(env)._do_import(filename, sheet, req, filename, ImporterTestCase.TICKET_TIME)
#sys.stdout = tempstdout
#req.display(template, content_type or 'text/html')
#open('/tmp/out.html', 'w').write(req.hdf.render(template, None))
_exec(cursor, "select * from ticket")
tickets = cursor.fetchall()
_exec(cursor, "select * from ticket_custom")
tickets_custom = cursor.fetchall()
_exec(cursor, "select * from ticket_change")
tickets_change = cursor.fetchall()
_exec(cursor, "select * from enum")
enums = [f for f in set(cursor.fetchall()) - set(enums_before)]
_exec(cursor, "select * from component")
components = [f for f in set(cursor.fetchall()) - set(components_before)]
pp = pprint.PrettyPrinter(indent=4)
return pp.pformat([ tickets, tickets_custom, tickets_change, enums, components ])
示例4: test_timezones
def test_timezones(self):
self.out.config.set('irclogs', 'timezone', 'America/New_York')
self.out.update_index()
req = Request(self._make_environ(), None)
req.session = {'tz': 'America/New_York'}
req.perm = Mock(has_permission= lambda x: True)
results = [i for i in self.out.get_search_results(req, ('hello',), ('irclogs',))]
self.assertEqual(20, len(results))
self.assertEqual((self.dt.hour-5+24)%24, results[0][2].hour)
示例5: test_write_unicode
def test_write_unicode(self):
buf = StringIO()
def write(data):
buf.write(data)
def start_response(status, headers):
return write
environ = self._make_environ(method='HEAD')
req = Request(environ, start_response)
req.send_header('Content-Type', 'text/plain;charset=utf-8')
req.write(u'Föö')
self.assertEqual('Föö', buf.getvalue())
示例6: location
def location(ua):
status_sent = []
headers_sent = {}
def start_response(status, headers):
status_sent.append(status)
headers_sent.update(dict(headers))
environ = self._make_environ(method='POST', HTTP_USER_AGENT=ua)
req = Request(environ, start_response,)
req.session = Mock(save=lambda: None)
self.assertRaises(RequestDone, req.redirect, url)
self.assertEqual('303 See Other', status_sent[0])
return headers_sent['Location']
示例7: send_project_index
def send_project_index(environ, start_response, parent_dir=None,
env_paths=None):
req = Request(environ, start_response)
loadpaths = [pkg_resources.resource_filename('trac', 'templates')]
if req.environ.get('trac.env_index_template'):
env_index_template = req.environ['trac.env_index_template']
tmpl_path, template = os.path.split(env_index_template)
loadpaths.insert(0, tmpl_path)
else:
template = 'index.html'
data = {'trac': {'version': TRAC_VERSION,
'time': user_time(req, format_datetime)},
'req': req}
if req.environ.get('trac.template_vars'):
for pair in req.environ['trac.template_vars'].split(','):
key, val = pair.split('=')
data[key] = val
try:
href = Href(req.base_path)
projects = []
for env_name, env_path in get_environments(environ).items():
try:
env = open_environment(env_path,
use_cache=not environ['wsgi.run_once'])
proj = {
'env': env,
'name': env.project_name,
'description': env.project_description,
'href': href(env_name)
}
except Exception as e:
proj = {'name': env_name, 'description': to_unicode(e)}
projects.append(proj)
projects.sort(lambda x, y: cmp(x['name'].lower(), y['name'].lower()))
data['projects'] = projects
loader = TemplateLoader(loadpaths, variable_lookup='lenient',
default_encoding='utf-8')
tmpl = loader.load(template)
stream = tmpl.generate(**data)
if template.endswith('.xml'):
output = stream.render('xml')
req.send(output, 'text/xml')
else:
output = stream.render('xhtml', doctype=DocType.XHTML_STRICT,
encoding='utf-8')
req.send(output, 'text/html')
except RequestDone:
pass
示例8: test_redirect
def test_redirect(self):
status_sent = []
headers_sent = {}
def start_response(status, headers):
status_sent.append(status)
headers_sent.update(dict(headers))
environ = self._make_environ(method='HEAD')
req = Request(environ, start_response)
req.session = Mock(save=lambda: None)
self.assertRaises(RequestDone, req.redirect, '/trac/test')
self.assertEqual('302 Found', status_sent[0])
self.assertEqual('http://example.org/trac/test',
headers_sent['Location'])
示例9: test_write_unicode
def test_write_unicode(self):
buf = StringIO()
def write(data):
buf.write(data)
def start_response(status, headers):
return write
environ = self._make_environ(method='HEAD')
req = Request(environ, start_response)
req.send_header('Content-Type', 'text/plain;charset=utf-8')
req.send_header('Content-Length', 0)
# anyway we're not supposed to send unicode, so we get a ValueError
self.assertRaises(ValueError, req.write, u'Föö')
示例10: test_write_iterable
def test_write_iterable(self):
buf = StringIO()
def write(data):
buf.write(data)
def start_response(status, headers):
return write
environ = self._make_environ(method='GET')
buf = StringIO()
req = Request(environ, start_response)
req.send_header('Content-Type', 'text/plain;charset=utf-8')
req.write(('Foo', 'bar', 'baz'))
self.assertEqual('Foobarbaz', buf.getvalue())
示例11: _test_preview
def _test_preview(self, env, filename):
req = Request({'SERVER_PORT': 0, 'SERVER_NAME': 'any', 'wsgi.url_scheme': 'any', 'wsgi.input': 'any', 'REQUEST_METHOD': 'GET' }, lambda x, y: _printme)
try:
from trac.test import MockPerm
req.perm = MockPerm()
except ImportError:
pass
req.authname = 'testuser'
req.hdf = HDFWrapper([]) # replace by this if you want to generate HTML: req.hdf = HDFWrapper(loadpaths=chrome.get_all_templates_dirs())
template, content_type = ImportModule(env)._do_preview(filename, 1, req)
#sys.stdout = tempstdout
#req.display(template, content_type or 'text/html')
#open('/tmp/out.html', 'w').write(req.hdf.render(template, None))
return str(req.hdf) + "\n"
示例12: test_write_unicode
def test_write_unicode(self):
buf = StringIO()
def write(data):
buf.write(data)
def start_response(status, headers):
return write
environ = self._make_environ(method="HEAD")
req = Request(environ, start_response)
req.send_header("Content-Type", "text/plain;charset=utf-8")
req.write(u"Föö")
self.assertEqual("Föö", buf.getvalue())
示例13: my_redirect
def my_redirect(*args, **kwords):
# Munge the cookie path
if 'trac_auth' in req.outcookie:
assert not self.uri_root.startswith('http'), 'The tracforge uri_root must be set to relative path'
req.outcookie['trac_auth']['path'] = self.uri_root
# Check to see if we should refer back to sibling Trac
referer = req.args.get('referer')
self.log.debug('TracForgeCookieMunger: Got referer as %r'%referer)
if referer:
parts = urlsplit(referer or '')
self.log.debug('TracForgeCookieMunger: parts=%s name=%r'%(parts,req.server_name))
if parts[2].startswith(self.uri_root) and (not parts[1] or parts[1] == req.server_name):
Request.redirect(req, referer)
old_redirect(req, *args, **kwords)
示例14: _make_req
def _make_req(environ, start_response, args={}, arg_list=(), authname='admin',
form_token='A' * 40, chrome={'links': {}, 'scripts': []},
perm=MockPerm(), session={}, tz=utc, locale=None, **kwargs):
req = Request(environ, start_response)
req.args = args
req.arg_list = arg_list
req.authname = authname
req.form_token = form_token
req.chrome = chrome
req.perm = perm
req.session = session
req.tz = tz
req.locale = locale
for name, value in kwargs.iteritems():
setattr(req, name, value)
return req
示例15: test_index_and_search
def test_index_and_search(self):
self.out.update_index()
req = Request(self._make_environ(), None)
req.session = {'tz': 'UTC'}
req.perm = Mock(has_permission= lambda x: True)
results = [i for i in self.out.get_search_results(req, ('hello',), ('irclogs',))]
self.assertEqual(20, len(results))
self.assertEqual(self.dt.hour, results[0][2].hour)
req.session = {'tz': 'America/New_York'}
req.perm = Mock(has_permission= lambda x: True)
results = [i for i in self.out.get_search_results(req, ('hello',), ('irclogs',))]
self.assertEqual(20, len(results))
est = timezone('America/New_York')
expect_dt = est.normalize(self.dt.astimezone(est))
sorted_results = sorted(results, key=operator.itemgetter(2))
self.assertEqual(expect_dt, sorted_results[0][2])