本文整理汇总了Python中trac.web.api.Request类的典型用法代码示例。如果您正苦于以下问题:Python Request类的具体用法?Python Request怎么用?Python Request使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Request类的19个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:Stackato-Apps,项目名称:bloodhound,代码行数:29,代码来源:util.py
示例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
开发者ID:trac-hacks,项目名称:trac-oidc,代码行数:25,代码来源:test_trac_oidc.py
示例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 ])
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:34,代码来源:test.py
示例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)
开发者ID:dokipen,项目名称:trac-irclogs-plugin,代码行数:9,代码来源:search.py
示例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())
开发者ID:gdgkyoto,项目名称:kyoto-gtug,代码行数:11,代码来源:api.py
示例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']
开发者ID:pkdevbox,项目名称:trac,代码行数:12,代码来源:api.py
示例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
开发者ID:pkdevbox,项目名称:trac,代码行数:53,代码来源:main.py
示例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'])
开发者ID:dafrito,项目名称:trac-mirror,代码行数:13,代码来源:api.py
示例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öö')
开发者ID:dafrito,项目名称:trac-mirror,代码行数:13,代码来源:api.py
示例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())
开发者ID:pkdevbox,项目名称:trac,代码行数:13,代码来源:api.py
示例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"
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:14,代码来源:test.py
示例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())
开发者ID:cyphactor,项目名称:lifecyclemanager,代码行数:14,代码来源:api.py
示例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)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:16,代码来源:auth.py
示例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
开发者ID:pkdevbox,项目名称:trac,代码行数:16,代码来源:api.py
示例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])
开发者ID:dokipen,项目名称:trac-irclogs-plugin,代码行数:16,代码来源:search.py
示例16: test_update
def test_update(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.out.update_index()
results = [i for i in self.out.get_search_results(req, ('hello',), ('irclogs',))]
self.assertEqual(40, len(results))
self.out.update_index()
results = [i for i in self.out.get_search_results(req, ('hello',), ('irclogs',))]
self.assertEqual(60, len(results))
self.out.update_index()
results = [i for i in self.out.get_search_results(req, ('hello',), ('irclogs',))]
self.assertEqual(80, len(results))
开发者ID:dokipen,项目名称:trac-irclogs-plugin,代码行数:16,代码来源:search.py
示例17: test_saved_custom_query_redirect
def test_saved_custom_query_redirect(self):
query = u'query:?type=résumé'
with self.env.db_transaction as db:
cursor = db.cursor()
cursor.execute("INSERT INTO report (title,query,description) "
"VALUES (%s,%s,%s)", ('redirect', query, ''))
id = db.get_last_id(cursor, 'report')
headers_sent = {}
def start_response(status, headers):
headers_sent.update(dict(headers))
environ = self._make_environ()
req = Request(environ, start_response)
req.authname = 'anonymous'
req.session = Mock(save=lambda: None)
self.assertRaises(RequestDone,
self.report_module._render_view, req, id)
self.assertEqual('http://example.org/trac/query?' + \
'type=r%C3%A9sum%C3%A9&report=' + str(id),
headers_sent['Location'])
开发者ID:pkdevbox,项目名称:trac,代码行数:20,代码来源:report.py
示例18: test_read_size
def test_read_size(self):
environ = self._make_environ(**{"wsgi.input": StringIO("test input")})
req = Request(environ, None)
self.assertEqual("test", req.read(size=4))
开发者ID:cyphactor,项目名称:lifecyclemanager,代码行数:4,代码来源:api.py
示例19: invoke
def invoke(self, chgset):
# regular expressions
ticket_prefix = "(?:#|(?:ticket|issue|bug)[: ]?)"
if self.intertrac: # TODO: split to separate function?
# find intertrac links
intertrac = {}
aliases = {}
for key, value in self.env.config.options("intertrac"):
if "." in key:
name, type_ = key.rsplit(".", 1)
if type_ == "url":
intertrac[name] = value
else:
aliases.setdefault(value, []).append(key)
intertrac = dict([(value, [key] + aliases.get(key, [])) for key, value in intertrac.items()])
project = os.path.basename(self.env.path)
if "/%s" % project in intertrac: # TODO: checking using base_url for full paths:
ticket_prefix = "(?:%s):%s" % ("|".join(intertrac["/%s" % project]), ticket_prefix)
else: # hopefully sesible default:
ticket_prefix = "%s:%s" % (project, ticket_prefix)
ticket_reference = ticket_prefix + "[0-9]+"
ticket_command = r"(?P<action>[A-Za-z]*).?" "(?P<ticket>%s(?:(?:[, &]*|[ ]?and[ ]?)%s)*)" % (
ticket_reference,
ticket_reference,
)
ticket_command = r"%s%s%s" % (re.escape(self.envelope_open), ticket_command, re.escape(self.envelope_close))
command_re = re.compile(ticket_command, re.IGNORECASE)
ticket_re = re.compile(ticket_prefix + "([0-9]+)", re.IGNORECASE)
# other variables
msg = "(In [%s]) %s" % (chgset.rev, chgset.message)
now = chgset.date
supported_cmds = {} # TODO: this could become an extension point
supported_cmds.update(dict([(key, self._cmdClose) for key in self.cmd_close]))
supported_cmds.update(dict([(key, self._cmdRefs) for key in self.cmd_refs]))
cmd_groups = command_re.findall(msg)
tickets = {}
for cmd, tkts in cmd_groups:
func = supported_cmds.get(cmd.lower(), None)
if func:
for tkt_id in ticket_re.findall(tkts):
tickets.setdefault(tkt_id, []).append(func)
for tkt_id, cmds in tickets.iteritems():
try:
db = self.env.get_db_cnx()
ticket = Ticket(self.env, int(tkt_id), db)
for cmd in cmds:
cmd(ticket)
# determine comment sequence number
cnum = 0
tm = TicketModule(self.env)
for change in tm.grouped_changelog_entries(ticket, db):
if change["permanent"]:
cnum += 1
# validate the ticket
# fake a request
# XXX cargo-culted environ from
# http://trac.edgewall.org/browser/trunk/trac/web/tests/api.py
environ = {
"wsgi.url_scheme": "http",
"wsgi.input": StringIO(""),
"SERVER_NAME": "0.0.0.0",
"REQUEST_METHOD": "POST",
"SERVER_PORT": 80,
"SCRIPT_NAME": "/" + self.env.project_name,
"REMOTE_USER": chgset.author,
"QUERY_STRING": "",
}
req = Request(environ, None)
req.args["comment"] = msg
req.authname = chgset.author
req.perm = PermissionCache(self.env, req.authname)
for manipulator in tm.ticket_manipulators:
manipulator.validate_ticket(req, ticket)
msg = req.args["comment"]
ticket.save_changes(chgset.author, msg, now, db, cnum + 1)
db.commit()
tn = TicketNotifyEmail(self.env)
tn.notify(ticket, newticket=0, modtime=now)
except Exception, e:
message = "Unexpected error while processing ticket ID %s: %s" % (tkt_id, repr(e))
print >>sys.stderr, message
self.env.log.error("TicketChanger: " + message)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:95,代码来源:ticketchanger.py
注:本文中的trac.web.api.Request类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论