本文整理汇总了Python中trac.env.Environment.get_db_cnx方法的典型用法代码示例。如果您正苦于以下问题:Python Environment.get_db_cnx方法的具体用法?Python Environment.get_db_cnx怎么用?Python Environment.get_db_cnx使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类trac.env.Environment
的用法示例。
在下文中一共展示了Environment.get_db_cnx方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: rename_user
# 需要导入模块: from trac.env import Environment [as 别名]
# 或者: from trac.env.Environment import get_db_cnx [as 别名]
def rename_user(envpath, oldname, newname):
"""Deletes all watchlist DB entries => Uninstaller"""
from trac.env import Environment
try:
env = Environment(envpath)
except:
print "Given path '%s' seems not to be a Trac environment." % envpath
sys.exit(3)
db = env.get_db_cnx()
cursor = db.cursor()
try:
cursor.execute("""
UPDATE watchlist
SET wluser=%s
WHERE wluser=%s
""", (newname,oldname))
cursor.execute("""
UPDATE watchlist_settings
SET wluser=%s
WHERE wluser=%s
""", (newname,oldname))
print "Renamed user '%s' to '%s'." % (oldname,newname)
db.commit()
except Exception as e:
db.rollback()
print "Could not rename user: " + unicode(e)
print "Does the new user already exists?"
sys.exit(3)
db.commit()
print "Finished."
示例2: EnvironmentTestCase
# 需要导入模块: from trac.env import Environment [as 别名]
# 或者: from trac.env.Environment import get_db_cnx [as 别名]
class EnvironmentTestCase(unittest.TestCase):
def setUp(self):
env_path = os.path.join(tempfile.gettempdir(), 'trac-tempenv')
self.env = Environment(env_path, create=True)
self.db = self.env.get_db_cnx()
def tearDown(self):
self.db.close()
self.env.shutdown() # really closes the db connections
shutil.rmtree(self.env.path)
def test_get_version(self):
"""Testing env.get_version"""
assert self.env.get_version() == db_default.db_version
def test_get_known_users(self):
"""Testing env.get_known_users"""
cursor = self.db.cursor()
cursor.executemany("INSERT INTO session VALUES (%s,%s,0)",
[('123', 0),('tom', 1), ('joe', 1), ('jane', 1)])
cursor.executemany("INSERT INTO session_attribute VALUES (%s,%s,%s,%s)",
[('123', 0, 'email', '[email protected]'),
('tom', 1, 'name', 'Tom'),
('tom', 1, 'email', '[email protected]'),
('joe', 1, 'email', '[email protected]'),
('jane', 1, 'name', 'Jane')])
users = {}
for username,name,email in self.env.get_known_users(self.db):
users[username] = (name, email)
assert not users.has_key('anonymous')
self.assertEqual(('Tom', '[email protected]'), users['tom'])
self.assertEqual((None, '[email protected]'), users['joe'])
self.assertEqual(('Jane', None), users['jane'])
示例3: fetchRecipes
# 需要导入模块: from trac.env import Environment [as 别名]
# 或者: from trac.env.Environment import get_db_cnx [as 别名]
def fetchRecipes(trac_env):
env = Environment(trac_env)
db = env.get_db_cnx()
cursor = db.cursor()
cursor.execute("SELECT path,active,recipe,min_rev,max_rev,label,description,name FROM bitten_config")
for row in cursor:
(path, active, recipe, min_rev, max_rev, label, description, name) = row
writeFile(trac_env, name, (path, active, recipe, min_rev, max_rev, label, description))
示例4: Main
# 需要导入模块: from trac.env import Environment [as 别名]
# 或者: from trac.env.Environment import get_db_cnx [as 别名]
def Main(opts):
""" Cross your fingers and pray """
env = Environment(opts.envpath)
from tractags.api import TagSystem
tlist = opts.tags or split_tags(env.config.get('blog', 'default_tag',
'blog'))
tags = TagSystem(env)
req = Mock(perm=MockPerm())
blog = tags.query(req, ' '.join(tlist + ['realm:wiki']))
cnx = env.get_db_cnx()
for resource, page_tags in list(blog):
try:
page = WikiPage(env, version=1, name=resource.id)
_, publish_time, author, _, _ = page.get_history().next()
if opts.deleteonly:
page.delete()
continue
categories = ' '.join([t for t in page_tags if t not in tlist])
page = WikiPage(env, name=resource.id)
for version, version_time, version_author, version_comment, \
_ in page.get_history():
# Currently the basename of the post url is used due to
# http://trac-hacks.org/ticket/2956
#name = resource.id.replace('/', '_')
name = resource.id
# extract title from text:
fulltext = page.text
match = _title_split_match(fulltext)
if match:
title = match.group(1)
fulltext = match.group(2)
else:
title = name
body = fulltext
print "Adding post %s, v%s: %s" % (name, version, title)
insert_blog_post(cnx, name, version, title, body,
publish_time, version_time,
version_comment, version_author, author,
categories)
reparent_blog_attachments(env, resource.id, name)
continue
cnx.commit()
if opts.delete:
page.delete()
continue
except:
env.log.debug("Error loading wiki page %s" % resource.id,
exc_info=True)
print "Failed to add post %s, v%s: %s" % (name, version, title)
cnx.rollback()
cnx.close()
return 1
cnx.close()
return 0
示例5: get_trac_user
# 需要导入模块: from trac.env import Environment [as 别名]
# 或者: from trac.env.Environment import get_db_cnx [as 别名]
def get_trac_user(path, username):
from trac.env import Environment
env = Environment(path)
db = env.get_db_cnx()
cursor = db.cursor()
cursor.execute(
"SELECT name, value" " FROM session_attribute" " WHERE sid='%s'" " AND (name='email' OR name='name')" % username
)
return dict((name, value) for name, value in cursor)
示例6: TracDatabase
# 需要导入模块: from trac.env import Environment [as 别名]
# 或者: from trac.env.Environment import get_db_cnx [as 别名]
class TracDatabase(object):
def __init__(self, path):
self.env = Environment(path)
self._db = self.env.get_db_cnx()
def db(self):
return self._db
def hasTickets(self):
c = self.db().cursor()
c.execute("SELECT count(*) FROM Ticket")
return int(c.fetchall()[0][0]) > 0
def setList(self, name, values):
c = self.db().cursor()
c.execute("DELETE FROM %s" % name)
for v in values:
print " inserting %s '%s'" % (name, v)
c.execute("INSERT INTO " + name + " (name) VALUES (%s)", (v,))
self.db().commit()
def setEnumList(self, name, values):
c = self.db().cursor()
c.execute("DELETE FROM enum WHERE type=%s", (name,))
for n, v in enumerate(values):
print " inserting %s '%s'" % (name, v)
c.execute("INSERT INTO enum (type, name, value) VALUES (%s,%s,%s)",
(name, v, n))
self.db().commit()
def clean(self):
print "\nCleaning all tickets..."
c = self.db().cursor()
c.execute("DELETE FROM ticket_change")
c.execute("DELETE FROM ticket")
c.execute("DELETE FROM attachment")
c.execute("DELETE FROM ticket_custom")
self.db().commit()
attachments_dir = os.path.join(os.path.normpath(self.env.path),
"attachments")
remove_recursively(attachments_dir)
if not os.path.isdir(attachments_dir):
os.mkdir(attachments_dir)
def addAttachment(self, ticket_id, filename, datafile, filesize,
author, description, upload_time):
# copied from bugzilla2trac
attachment = Attachment(self.env, 'ticket', ticket_id)
attachment.author = author
attachment.description = description
attachment.insert(filename, datafile, filesize, upload_time)
del attachment
示例7: do_purge
# 需要导入模块: from trac.env import Environment [as 别名]
# 或者: from trac.env.Environment import get_db_cnx [as 别名]
def do_purge(self, req, path, users):
"""Purge obsolete data - i.e. environment data (sessions, preferences,
permissions) from users no longer existing
@param req
@param path path to the trac env to purge
@param users users to keep
@return boolean success
@return msg info
"""
self.env.log.debug('+ Purging obsolete data')
dryrun = self.env.config.getbool('user_sync','dryrun',True)
sql = []
envpath, tracenv = os.path.split(path)
try:
env = Environment(path)
except IOError:
self.env.log.debug('Could not initialize environment at %s' % (path,))
return False, 'Could not initialize environment at %s' % (path,)
perm = PermissionSystem(env)
if not 'TRAC_ADMIN' in perm.get_user_permissions(req.perm.username):
raise PermissionError
excludes = self.get_perm_groups(path)+users
protect = "'"+"','".join(excludes)+"'"
self.env.log.debug("Excluding from purge: %s" % (protect,))
db = env.get_db_cnx()
cursor = db.cursor()
if not dryrun:
self.env.log.debug('Updating database for %s' % (tracenv,))
cursor.execute('DELETE FROM auth_cookie WHERE name NOT IN (%s)' % (protect,))
cursor.execute('DELETE FROM session WHERE sid NOT IN (%s)' % (protect,))
cursor.execute('DELETE FROM session_attribute WHERE sid NOT IN (%s)' % (protect,))
cursor.execute('DELETE FROM permission WHERE username NOT IN (%s)' % (protect,))
db.commit()
sql_file_path = self.env.config.get('user_sync','sql_file_path') or os.path.join(self.env.path,'log')
if sql_file_path.lower() == 'none':
self.env.log.debug('SQLFile disabled (sql_file_path is "none")')
else:
sqlfile = '%s.sql' % (tracenv,)
sqlfile = os.path.join(sql_file_path,sqlfile)
self.env.log.debug('Writing SQL to %s' % (sqlfile,))
try:
f = open(sqlfile,'a')
f.write('\n--- SQL for purging Trac environment %s\n' % (tracenv,));
f.write('DELETE FROM auth_cookie WHERE name NOT IN (%s);\n' % (protect,))
f.write('DELETE FROM session WHERE sid NOT IN (%s);\n' % (protect,))
f.write('DELETE FROM session_attribute WHERE sid NOT IN (%s);\n' % (protect,))
f.write('DELETE FROM permission WHERE username NOT IN (%s);\n' % (protect,))
except IOError:
self.env.log.debug('Could not write SQL file %s!' % (sqlfile,))
return False, 'Could not write SQL file %s!' % (sqlfile,)
return True, 'Successfully purged environment %s' % (tracenv,)
示例8: TicketTemplateTestCase
# 需要导入模块: from trac.env import Environment [as 别名]
# 或者: from trac.env.Environment import get_db_cnx [as 别名]
class TicketTemplateTestCase(unittest.TestCase):
def setUp(self):
# self.env = EnvironmentStub()
env_path = os.path.join(tempfile.gettempdir(), 'trac-tempenv')
self.env = Environment(env_path, create=True)
self.db = self.env.get_db_cnx()
self.compmgr = ComponentManager()
# init TicketTemplateModule
self.tt = ttadmin.TicketTemplateModule(self.compmgr)
setattr(self.tt, "env", self.env)
def tearDown(self):
self.db.close()
self.env.shutdown() # really closes the db connections
shutil.rmtree(self.env.path)
def test_get_active_navigation_item(self):
req = Mock(path_info='/tickettemplate')
self.assertEqual('tickettemplate', self.tt.get_active_navigation_item(req))
req = Mock(path_info='/something')
self.assertNotEqual('tickettemplate', self.tt.match_request(req))
def test_get_navigation_items(self):
req = Mock(href=Mock(tickettemplate=lambda:"/trac-tempenv/tickettemplate"))
a, b, c= self.tt.get_navigation_items(req).next()
self.assertEqual('mainnav', a)
self.assertEqual('tickettemplate', b)
def test_match_request(self):
req = Mock(path_info='/tickettemplate')
self.assertEqual(True, self.tt.match_request(req))
req = Mock(path_info='/something')
self.assertEqual(False, self.tt.match_request(req))
def test_getTicketTypeNames(self):
options = self.tt._getTicketTypeNames()
self.assertEqual(["default", "defect", "enhancement", "task"], options)
def test_loadSaveTemplateText(self):
for tt_name, tt_text in [("default", "default text"),
("defect", "defect text"),
("enhancement", "enhancement text"),
("task", "task text"),
]:
self.tt._saveTemplateText(tt_name, tt_text)
self.assertEqual(tt_name + " text", self.tt._loadTemplateText(tt_name))
示例9: _setup
# 需要导入模块: from trac.env import Environment [as 别名]
# 或者: from trac.env.Environment import get_db_cnx [as 别名]
def _setup(self, configuration = None):
configuration = configuration or '[ticket-custom]\nmycustomfield = text\nmycustomfield.label = My Custom Field\nmycustomfield.order = 1'
instancedir = os.path.join(tempfile.gettempdir(), 'test-importer._preview')
if os.path.exists(instancedir):
shutil.rmtree(instancedir, False)
env = Environment(instancedir, create=True)
open(os.path.join(os.path.join(instancedir, 'conf'), 'trac.ini'), 'a').write('\n' + configuration + '\n')
db = env.get_db_cnx()
_exec(db.cursor(), "INSERT INTO permission VALUES ('anonymous', 'REPORT_ADMIN') ")
_exec(db.cursor(), "INSERT INTO permission VALUES ('anonymous', 'IMPORT_EXECUTE') ")
db.commit()
ImporterTestCase.TICKET_TIME = 1190909220
return Environment(instancedir)
示例10: get_number_of_tickets_per_cr
# 需要导入模块: from trac.env import Environment [as 别名]
# 或者: from trac.env.Environment import get_db_cnx [as 别名]
def get_number_of_tickets_per_cr(self, project):
settings = get_current_registry().settings
if not settings:
return
tracenvs = settings.get('penelope.trac.envs')
for trac in project.tracs:
env = Environment('%s/%s' % (tracenvs, trac.trac_name))
db = env.get_db_cnx()
cursor = db.cursor()
cursor.execute("""SELECT c.value as cr, count(t.id) AS number FROM ticket t INNER JOIN ticket_custom c ON (t.id = c.ticket AND c.name = 'customerrequest') group by cr;""")
tickets = cursor.fetchall()
db.rollback()
return dict(tickets)
示例11: get_perm_groups
# 需要导入模块: from trac.env import Environment [as 别名]
# 或者: from trac.env.Environment import get_db_cnx [as 别名]
def get_perm_groups(self,path):
"""Get array of permission groups (e.g. anonymous,authenticated) defined in the given environment.
These 'users' should e.g. never be purged on cleanup
"""
users = []
env = Environment(path)
sids = []
self.env.log.debug('Get users to keep from environment path %s' % (path,))
db = env.get_db_cnx()
cursor = db.cursor()
cursor.execute('SELECT DISTINCT username FROM permission WHERE username NOT IN (SELECT DISTINCT sid FROM session_attribute UNION SELECT DISTINCT sid FROM session UNION SELECT DISTINCT name FROM auth_cookie)')
for row in cursor: users.append(row[0])
self.env.log.debug('Permission groups for %s: %s' % (path,','.join(users)))
for user in env.config.getlist('user_sync','users_keep'):
if not user in users: users.append(user)
return users
示例12: getMySQLEnvironment
# 需要导入模块: from trac.env import Environment [as 别名]
# 或者: from trac.env.Environment import get_db_cnx [as 别名]
def getMySQLEnvironment(opts):
dburi = opts.mysql_uri
env = Environment(opts.tracenv)
env.config.set('trac', 'database', dburi)
try:
cnx = env.get_db_cnx()
cur = cnx.cursor()
cur.execute("select value from system where name = 'database_version'");
except ProgrammingError:
cnx.rollback()
DatabaseManager(env).init_db()
DatabaseManager(env).shutdown()
# if env.needs_upgrade():
# env.upgrade()
return env
示例13: get_tracenv_users
# 需要导入模块: from trac.env import Environment [as 别名]
# 或者: from trac.env.Environment import get_db_cnx [as 别名]
def get_tracenv_users(self, path, userlist=''):
"""Get array of users defined in the specified environment having data assigned
@param path path to the environment
@param userlist comma separated list of users to restrict the result to (e.g. the users from the password file), each user enclosed in single quotes (for SQL)
@return array [0..n] of string users
"""
env = Environment(path)
sids = []
self.env.log.debug('Get users from %s' % (path,))
db = env.get_db_cnx()
cursor = db.cursor()
if userlist:
cursor.execute("SELECT DISTINCT sid FROM session_attribute WHERE sid IN (%s) AND name != 'enabled'" % (userlist,))
else:
cursor.execute("SELECT DISTINCT sid FROM session_attribute WHERE name != 'enabled'")
for row in cursor:
sids.append(row[0])
return sids
示例14: get_tracenv_userdata
# 需要导入模块: from trac.env import Environment [as 别名]
# 或者: from trac.env.Environment import get_db_cnx [as 别名]
def get_tracenv_userdata(self, req, path, userlist=''):
"""Retrieve account data from the environment at the specified path
@param path path to the environment
@param userlist comma separated list of users to restrict the result to (e.g. the users from the password file), each user enclosed in single quotes (for SQL)
@return array (empty array if the environment uses a different password file than the master env calling us)
"""
self.env.log.debug('Get user data from %s' % (path,))
data = {}
env = Environment(path)
# if this environment uses a different password file, we return an empty dataset
if self.env.config.get('account-manager','password_file') != env.config.get('account-manager','password_file'):
self.env.log.info('Password files do not match, skipping environment %s' % (path,))
return data
perm = PermissionSystem(env)
if not 'TRAC_ADMIN' in perm.get_user_permissions(req.perm.username):
raise PermissionError
db = env.get_db_cnx()
cursor = db.cursor()
sync_fields = self.env.config.getlist('user_sync','sync_fields')
attr = "'"+"','".join(sync_fields)+"','email_verification_sent_to','email_verification_token'"
self.env.log.debug('* Checking attributes: %s' % (attr,))
if userlist:
cursor.execute("SELECT sid,name,value FROM session_attribute WHERE sid IN (%s) AND name IN (%s)" % (userlist,attr,))
else:
cursor.execute("SELECT sid,name,value FROM session_attribute WHERE name IN (%s)" % (attr,))
for row in cursor:
if not row[0] in data: data[row[0]] = {}
data[row[0]][row[1]] = row[2]
for sid in data.iterkeys():
no_data = True
for att in sync_fields:
if att in data[sid]:
no_data = False
break
if no_data:
self.env.log.debug('No data for %s in %s' % (sid,path,))
data[sid] = Null
continue
data[sid]['path'] = path
cursor.execute("SELECT authenticated FROM session_attribute WHERE sid='%s'" % (sid,))
for row in cursor: data[sid]['authenticated'] = row[0]
cursor.execute("SELECT datetime(last_visit,'unixepoch') AS last_visit FROM session WHERE sid='%s'" % (sid,))
for row in cursor: data[sid]['last_visit'] = row[0]
return data
示例15: getPostgreSQLEnvironment
# 需要导入模块: from trac.env import Environment [as 别名]
# 或者: from trac.env.Environment import get_db_cnx [as 别名]
def getPostgreSQLEnvironment(opts):
""" Create an Environment connected to the PostgreSQL database """
dburi = opts.pg_uri
env = Environment(opts.tracenv)
env.config.set('trac', 'database', dburi)
try:
cnx = env.get_db_cnx()
cur = cnx.cursor()
cur.execute("select value from system where name = 'database_version'");
except ProgrammingError:
cnx.rollback()
DatabaseManager(env).init_db()
DatabaseManager(env).shutdown()
for x in filter(None, [env.compmgr[cls] for cls in
ComponentMeta._registry.get(
IEnvironmentSetupParticipant, [])]):
if isinstance(x, EnvironmentSetup):
x.environment_created()
if env.needs_upgrade():
env.upgrade()
return env