本文整理汇总了Python中multiproject.common.projects.Project.get方法的典型用法代码示例。如果您正苦于以下问题:Python Project.get方法的具体用法?Python Project.get怎么用?Python Project.get使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类multiproject.common.projects.Project
的用法示例。
在下文中一共展示了Project.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: post_process_request
# 需要导入模块: from multiproject.common.projects import Project [as 别名]
# 或者: from multiproject.common.projects.Project import get [as 别名]
def post_process_request(self, req, template, data, content_type):
#add_script(req, 'multiproject/js/browser.js')
repository_name = None
data_repositories = None
latest_revisions = []
if len(req.path_info.split("/")) > 2:
#Get repository name from path_info
repository_name = req.path_info.split("/")[2]
if template == 'browser.html':
username = urllib.quote(req.authname)
project = Project.get(self.env)
schemes = None
if repository_name:
scm_type = repository_name + ".type"
scm_dir = repository_name + ".dir"
scm = self.env.config.get('repositories', scm_type)
repository_name = self.env.config.get('repositories', scm_dir).split("/")[-1]
schemes = self.protocols(project.id, scm)
rm = RepositoryManager(self.env)
list_repos = rm.get_real_repositories()
for r in list_repos:
if r.get_base().split("/")[-1] == repository_name:
l_rev = r.get_youngest_rev()
if l_rev:
export_url = '../export/archive/'+repository_name+"?rev="+str(l_rev)+"&format=zip"
latest_revisions.append(export_url)
else:
scm = self.env.config.get('trac', 'repository_type')
schemes = self.protocols(project.id, scm)
data_repo_names = self.get_repositories()
if len(data_repo_names) > 0:
data_repositories = []
for repo in data_repo_names:
type_scheme = []
for data_scheme in self.protocols(project.id, repo[1]):
type_scheme.append(self.create_co_command(repo[1], username, data_scheme, repo[0]))
data_repositories.append(type_scheme)
names = {'git':'GIT', 'svn':'Subversion', 'hg':'Mercurial'}
cmd_kinds = {'git':'Clone', 'hg':'Clone', 'svn':'Check out'}
type = names[scm]
data['kinds'] = cmd_kinds
data['schemes'] = schemes
data['name'] = names[scm]
data['type'] = scm
data['data_repositories'] = data_repositories
data['export_urls'] = latest_revisions
co_commands = {}
for scheme in schemes:
co_commands[scheme] = self.create_co_command(scm, username, scheme, repository_name)
data['co_commands'] = co_commands
return template, data, content_type
示例2: render_admin_panel
# 需要导入模块: from multiproject.common.projects import Project [as 别名]
# 或者: from multiproject.common.projects.Project import get [as 别名]
def render_admin_panel(self, req, category, page, path_info):
"""
Process a request for an admin panel.
:Returns: A tuple of the form `(template, data)`,
"""
# Ensure the user has project admin permissions
req.perm.assert_permission('TRAC_ADMIN')
backups = []
backup_href = Href('%s/admin/general/backup' % req.base_path)
# Load the user based on authname
user = get_userstore().getUser(req.authname)
# Get the current environment name
env_name = conf.resolveProjectName(self.env)
# Initiate ProjectBackup, containing the backup/restore implementation
prj = Project.get(env_name=env_name)
pb = ProjectBackup(prj)
backups = pb.get_backups()
# Do the backup
if req.path_info.endswith('backup/backup') and req.method == 'POST':
try:
pb.backup(user_id=user.id, description=req.args.get('description'))
add_notice(req, _('Backup created'))
except TracError, e:
add_warning(req, _('Backup failed: %s' % e))
# Return back to default backup page
return req.redirect(backup_href())
示例3: target_node
# 需要导入模块: from multiproject.common.projects import Project [as 别名]
# 或者: from multiproject.common.projects.Project import get [as 别名]
def target_node(self):
if self._target_node is not None:
return self._target_node
env_name = self.environment_identifier()
if not env_name:
conf.log.warning("Failed reading identifier")
raise NodeError('Target node was invalid: env_name not found')
project = Project.get(env_name=env_name)
# env_name might be different from project.env_name!
base_url = project.get_dav_url(relative=True)
path_info = normalized_base_url(self.req.uri)
project_id = project.id
download_config = FilesDownloadConfig(project.env_name, base_url=base_url)
if not path_info.startswith(download_config.base_url):
raise NodeError('Target node was invalid: uri %s does not start with %s',
path_info, base_url)
self._download_config = download_config
try:
node_factory = MappedFileNode(project_id,
download_config.base_path, download_config.base_url, download_config.downloads_dir)
self._target_node = MappedFileNode.from_request_path_info(path_info, node_factory)
except Exception as e:
conf.log.warning("Not node %s", str(e))
raise NodeError('Target node was invalid: %s', str(e))
return self._target_node
示例4: render_admin_panel
# 需要导入模块: from multiproject.common.projects import Project [as 别名]
# 或者: from multiproject.common.projects.Project import get [as 别名]
def render_admin_panel(self, req, cat, page, path_info):
"""
Returns the admin view and handles the form actions
"""
req.perm.require('TRAC_ADMIN')
project = Project.get(self.env)
if req.method == 'POST':
myprojects_url = conf.url_home_path + "/myprojects"
conf.log.exception("Redirect URL: %s" % myprojects_url)
thisurl = Href(req.base_path)(req.path_info)
context = Context.from_request(req)
# Handle project remove
if 'remove' in req.args:
# Don't allow removing home
if project.env_name == conf.sys_home_project_name:
add_warning(req, 'Cannot remove home project')
return req.redirect(thisurl)
# Archive the project before removal
archive = ProjectArchive()
archived = archive.archive(project)
if not archived:
add_warning(req, 'Could not archive project "%s". Will not remove the project' % project.project_name)
return req.redirect(thisurl)
# Notify listeners. The project object still exists, but database does not
for listener in self.project_change_listeners:
listener.project_archived(project)
# Do the actual project removal
projects = Projects()
if projects.remove_project(project):
# Notify listeners. The project object still exists, but database does not
for listener in self.project_change_listeners:
listener.project_deleted(project)
# NOTE: We no longer have project tables/session etc available
req.redirect(myprojects_url)
else:
add_warning(req, 'Could not remove project "%s". Try again later' % project.project_name)
return req.redirect(thisurl)
add_script(req, 'multiproject/js/jquery-ui.js')
add_script(req, 'multiproject/js/multiproject.js')
add_script(req, 'multiproject/js/admin_system.js')
add_stylesheet(req, 'multiproject/css/jquery-ui.css')
# NOTE: Trac automatically puts 'project' dict in chrome thus it cannot be used
data = {'multiproject': {
'project':project,
'home_url':conf.url_home_path
}}
return 'admin_system.html', data
示例5: remove_project
# 需要导入模块: from multiproject.common.projects import Project [as 别名]
# 或者: from multiproject.common.projects.Project import get [as 别名]
def remove_project(self, req):
"""
Handler for removing project
:param Request req: Trac request
Handler expects to have following arguments in it:
- project: Name of the project env
- goto: Optional URL where to go after project removal. Defaults to /home/myprojects
"""
backurl = req.args.get('goto', ProjectListModule.home('myprojects'))
short_name = req.args.get('project')
if not short_name:
return self.remove_failure(req)
if req.args.get('cancel'):
add_notice(req, 'Project deletion cancelled')
return self.remove_failure(req)
author = req.authname
project = Project.get(env_name=short_name)
if project is None:
add_warning(req, 'Specified project does not exist!')
return self.remove_failure(req)
# Don't allow removing home
if project.env_name == conf.sys_home_project_name:
add_warning(req, 'Cannot remove home project')
return self.remove_failure(req)
if req.method != 'POST':
return self.remove_failure(req, project=project)
try:
project.validate()
except ProjectValidationException:
req.redirect(backurl)
# Check the permissions and method
prjs = Projects()
if ('TRAC_ADMIN' in req.perm or prjs.is_project_owner(project.env_name, author)) and req.method == 'POST':
archive = ProjectArchive()
# Archive the project before removal
if not archive.archive(project):
add_warning(req, 'Could not archive project "%s". Will not remove the project' % project.project_name)
elif prjs.remove_project(project):
# Notify listeners
for listener in self.project_change_listeners:
listener.project_deleted(project)
# Notify end user
add_notice(req, 'Project "%s" removed' % project.project_name)
else:
add_warning(req, 'Could not remove project "%s". Try again later' % project.project_name)
else:
add_warning(req, 'You are not allowed to remove project "%s" (check permissions and method)' % project.project_name)
req.redirect(backurl)
示例6: process_request
# 需要导入模块: from multiproject.common.projects import Project [as 别名]
# 或者: from multiproject.common.projects.Project import get [as 别名]
def process_request(self, req):
""" Process request for listing, creating and removing projects
"""
add_script(req, 'multiproject/js/summary.js')
data = {}
if req.authname == 'anonymous':
req.perm.require('PROJECT_VIEW')
if not ('PROJECT_VIEW' in req.perm or 'PROJECT_PRIVATE_VIEW' in req.perm):
return 'no_access.html', data, None
# Load project from db
project = Project.get(self.env)
if req.args.get('action') == 'timeline_events':
return self.get_summary_timeline_events(req, project.created)
# TODO: Move project timeline implementation into macro
# Get recent timeline events
# TODO: Move project downloads implementation into macro
# Get list of featured downloads
downloads = []
if self.env.is_component_enabled('tracdownloads.api.DownloadsApi'):
api = None
# In case of import error we don't have it, so don't return any downloads
try:
from tracdownloads.api import DownloadsApi
api = DownloadsApi(self.env)
except ImportError:
self.log.warning("Unable to import DownloadsApi, but it's enabled.")
if api:
downloads = api.get_summary_items()
# Load wiki:SummaryPage and show it as a main page
summary_content = None
summary_wiki = WikiPage(self.env, 'SummaryPage')
if summary_wiki:
context = Context.from_request(req, summary_wiki.resource)
wiki_renderer = WikiTextRenderer(self.env)
summary_content = wiki_renderer.render(context, 'text/x-trac-wiki', summary_wiki.text)
data = {
'_project_': project, # project object of a project we are in
'downloads': downloads, # list of featured downloads
'wiki_summary': summary_content, # Rendered content of the SummaryPage
'is_summary': True,
'env': self.env,
}
return 'summary.html', data, None
示例7: render_admin_panel
# 需要导入模块: from multiproject.common.projects import Project [as 别名]
# 或者: from multiproject.common.projects.Project import get [as 别名]
def render_admin_panel(self, req, cat, page, path_info):
req.perm.require('TRAC_ADMIN')
protos = ProtocolManager(Project.get(self.env).id)
scm_type = self.env.config.get('trac', 'repository_type')
if req.method == 'POST':
self._process_changes(req, protos, scm_type)
return self._show_panel(req, protos, scm_type)
示例8: _notify_admins
# 需要导入模块: from multiproject.common.projects import Project [as 别名]
# 或者: from multiproject.common.projects.Project import get [as 别名]
def _notify_admins(self, permission, email_path, debug="false"):
is_debug = debug.lower() in ("true", "yes")
if permission != "TRAC_ADMIN":
raise AdminCommandError("Only TRAC_ADMIN permission is supported")
# A standard thing to do in IAdminCommandProviders (otherwise,
# accessing project_identifier would give errors)
if not hasattr(self.env, "project_identifier"):
MultiProjectEnvironmentInit(self.env).environment_needs_upgrade(None)
env_name = self.env.project_identifier
if env_name == self.env.config.get("multiproject", "sys_home_project_name"):
raise AdminCommandError("Command does not support home project")
if not os.path.exists(email_path):
raise AdminCommandError(_("Email template was not found!"))
project = Project.get(self.env)
email_template = ""
try:
with open(email_path) as fd:
email_template = fd.read()
except OSError as e:
raise AdminCommandError(_("Error with opening file %(path)s: %(error_msg)s", path=email_path, error_msg=e))
except Exception as e:
raise AdminCommandError(
_("Unknown error when parsing file %(path)s: %(error_msg)s", path=email_path, error_msg=e)
)
email_template = [i.strip() for i in email_template.split("\n", 1) if i]
if not len(email_template) > 1 or not all(email_template):
raise AdminCommandError(_("Email template %(path)s was invalid.", path=email_path))
subject, body = email_template
text_template = NewTextTemplate(body)
admins = project.get_admin_email_addresses()
data = {"env_name": env_name}
if is_debug:
printout("## DEBUG MODE - NOT SENDING EMAILS ##")
printout("project: {0}".format(env_name))
printout("to: {0}".format(",".join(admins)))
printout("subject: {0}".format(subject))
printout("----------------------------")
printout(text_template.generate(**data))
printout("----------------------------")
if not is_debug:
notifier = EmailNotifier(self.env, subject=subject, data=data)
notifier.template = text_template
notifier.notify(admins)
printout("Emails sent")
示例9: post_process_request
# 需要导入模块: from multiproject.common.projects import Project [as 别名]
# 或者: from multiproject.common.projects.Project import get [as 别名]
def post_process_request(self, req, template, data, content_type):
"""
Puts global ``mproject`` variable into data
"""
# Ensure the mproject is set
data = data or {'mproject': None}
if self.config.get('multiproject', 'sys_home_project_name', 'home') != self.env.path.split('/')[-1] and data:
project = Project.get(self.env)
data.update({'mproject': project})
return template, data, content_type
示例10: make_membership_request
# 需要导入模块: from multiproject.common.projects import Project [as 别名]
# 或者: from multiproject.common.projects.Project import get [as 别名]
def make_membership_request(self, req):
project = Project.get(self.env)
# Make a request
members = MembershipApi(self.env, project)
members.request_membership(req.authname, req.args.get('message'))
type = 'membership'
if req.args.has_key('type'):
type = req.args.get('type')
return 'membership_requested.html', {'_project_':project, 'type':type}, None
示例11: render_admin_panel
# 需要导入模块: from multiproject.common.projects import Project [as 别名]
# 或者: from multiproject.common.projects.Project import get [as 别名]
def render_admin_panel(self, req, cat, page, path_info):
""" Overrides BasicsAdminPanel rendering function.
Handle project info update (update global db) and then
delegate handling back to BasicsAdminPanel
"""
req.perm.require('TRAC_ADMIN')
userstore = get_userstore()
user = userstore.getUser(req.authname)
project = Project.get(self.env)
# Update database if form posted
if req.method == 'POST':
# Remove icon if requested
if 'reset' in req.args:
# NOTE: Icon is removed from filesystem already at this point
self._unset_icon(req, project)
project.icon_name = None
# Update icon if set
if not isinstance(req.args.get('icon', ''), basestring):
icon_name = self._set_icon(req, project)
if icon_name:
# If image is changed
if icon_name != project.icon_name:
self._unset_icon(req, project)
project.icon_name = icon_name
else:
add_warning(req, 'Failed to set the project icon')
# Save changes in database
if 'apply' in req.args:
self._apply_changes(req, project)
# Reload page
return req.redirect(req.href(req.path_info))
data = {
'user': user,
'icon_size': self.icon_size,
'mproject': project,
'allow_public_projects': conf.allow_public_projects
}
# Add javascript libraries for datepicker and autocomplete
add_script(req, 'multiproject/js/jquery-ui.js')
add_stylesheet(req, 'multiproject/css/jquery-ui.css')
add_script(req, 'multiproject/js/multiproject.js')
add_script(req, 'multiproject/js/admin_basics.js')
Chrome(self.env).add_textarea_grips(req)
return 'admin_basics_replacement.html', data
示例12: openProject
# 需要导入模块: from multiproject.common.projects import Project [as 别名]
# 或者: from multiproject.common.projects.Project import get [as 别名]
def openProject(self, req, projectname, revision, extensionlist):
""" Returns project's connection string and repository file list matched to search criteria.
"""
# Return values
if str(projectname).strip() == '':
e = exceptions.Exception
raise e("Incorrect project name")
if revision.strip() == '':
revision = None
if extensionlist.strip() == '':
extensionlist = None
# Find node for the requested path/rev
repomgr = RepositoryManager(self.env)
repository = repomgr.get_repository(None)
projectname = conf.cleanupProjectName(projectname)
parts = []
project = Project.get(env_name=projectname)
if project:
parts.append(self.get_scm_repository_url(project.env_name))
else:
return []
try:
if revision:
revision = repository.normalize_rev(revision)
rev_or_latest = revision or repository.youngest_rev
getfiles = []
self._getfiles(req, getfiles, repository, '', rev_or_latest)
if extensionlist:
extensions = extensionlist.split(',')
searchresult = []
for file in getfiles:
extension = os.path.splitext(str(file))[1].strip('.')
if extension in extensions:
searchresult.append(file)
addfiles = ",".join(searchresult)
else:
addfiles = ",".join(getfiles)
if addfiles:
# Append version control files
parts.append('versioncontrolfiles|' + addfiles)
except Exception:
self.log.exception("ProjectsRPC.openProject failed")
return parts
示例13: get_latest_timeline_events
# 需要导入模块: from multiproject.common.projects import Project [as 别名]
# 或者: from multiproject.common.projects.Project import get [as 别名]
def get_latest_timeline_events(self, req, count, project_created=None):
"""
Returns latest (within 10 days) timeline events.
If count is given, returns only given number of elements.
:param Request req: Trac request
:param int count: Number of elements to returns. Defaults to all
:returns: List of events
"""
events = []
available_filters = []
for event_provider in self.event_providers:
available_filters += event_provider.get_timeline_filters(req) or []
# TODO: make this incredibly obscure piece of code readable
# check the request or session for enabled filters, or use default
filters = []
filters_list = []
for afilter in available_filters:
filters_list.append(afilter[0])
filter_set = set(filters_list)
for item in filter_set:
filters.append(item)
# start time of timeline is last update of if not known, last two monts
if not project_created:
project = Project.get(self.env)
project_start_date = project.created
else:
project_start_date = project_created
project_start_date = project_start_date.replace (tzinfo = datefmt.localtz)
# do the actual event querying
for provider in self.event_providers:
todate = datetime.now(datefmt.localtz)
fromdate = todate - timedelta(days = 10)
eventcount = 0
while eventcount < count and todate > project_start_date:
for event in provider.get_timeline_events(req, fromdate, todate, filters):
eventcount += 1
events.append(self._event_data(provider, event))
todate = fromdate
fromdate = todate - timedelta(days = 10)
events.sort(lambda x, y: cmp(y['date'], x['date']))
# Note, when count = None, all the events are returned
return events[:count] if events else []
示例14: render_admin_panel
# 需要导入模块: from multiproject.common.projects import Project [as 别名]
# 或者: from multiproject.common.projects.Project import get [as 别名]
def render_admin_panel(self, req, cat, page, path_info):
req.perm.require('TRAC_ADMIN')
project = Project.get(self.env)
child_projects = project.get_child_projects()
data = {
'_project_': project,
'parent_project': project.parent_project,
'child_projects': child_projects,
'home': conf.url_home_path
}
add_script(req, 'multiproject/js/admin_relations.js')
return 'multiproject_admin_relations.html', data
示例15: notify_now
# 需要导入模块: from multiproject.common.projects import Project [as 别名]
# 或者: from multiproject.common.projects.Project import get [as 别名]
def notify_now(self, notification_frequency):
"""
Send notification email to project watchers.
:param str notification_frequency: The notification frequency, used to fetch
users which have something on that watchlist.
"""
store = CQDEWatchlistStore()
watches = store.get_by_notification(notification_frequency)
notifylist = {}
for w in watches:
if notifylist.get(w.project_id) is None:
notifylist[w.project_id] = []
notifylist[w.project_id].append(w.user_id)
userstore = get_userstore()
counter = 0
for project_id in notifylist.keys():
project = Project.get(id=project_id)
# Get all events for this project
events = self._get_project_events(project, notification_frequency)
# Send one email per user, because everyone may have a different
# set of permissions (i.e. which events he/she has permission to see)
for user_id in notifylist[project_id]:
user = userstore.getUserWhereId(user_id)
if user:
# filter eventlist by user's permissions
filtered_events = WatchlistEvents(self.env).filter_events(events, user, project)
if filtered_events:
addresses = [user.mail]
message = self._format_message(user, project, filtered_events)
title = "Project updated: %s" % project.env_name
mail = EmailNotifier(self.env, subject=title, data={'body':message})
mail.notify_emails(addresses)
self.env.log.debug('Sent email notification to: %s' % user)
counter += 1
else:
if notification_frequency != 'immediate':
self.env.log.debug('No events to sent to %s about %s' % (user, project))
else:
self.env.log.warning('User %d in notification list was not found in userstore' % user_id)
# Log the results
self.env.log.info('Sent %s watchlist notifications (%s)' % (counter, notification_frequency))