本文整理汇总了Python中zkpylons.model.config.Config类的典型用法代码示例。如果您正苦于以下问题:Python Config类的具体用法?Python Config怎么用?Python Config使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Config类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _new
def _new(self):
# Do we allow account creation?
if Config.get('account_creation'):
"""Create a new person submit.
"""
# Remove fields not in class
results = self.form_result['person']
del results['password_confirm']
c.person = Person(**results)
c.person.email_address = c.person.email_address.lower()
meta.Session.add(c.person)
#for sn in self.form_result['social_network']:
# network = SocialNetwork.find_by_name(sn['name'])
# if sn['account_name']:
# c.person.social_networks[network] = sn['account_name']
meta.Session.commit()
if Config.get('confirm_email_address', category='rego') == 'no':
redirect_to(controller='person', action='confirm', confirm_hash=c.person.url_hash)
else:
email(c.person.email_address, render('/person/new_person_email.mako'))
# return render('/person/thankyou.mako')
return self.finish_login(c.person.email_address)
else:
return render('/not_allowed.mako')
示例2: _edit
def _edit(self, id):
# We need to recheck auth in here so we can pass in the id
if not h.auth.authorized(h.auth.Or(h.auth.is_same_zkpylons_submitter(id), h.auth.has_organiser_role)):
# Raise a no_auth error
h.auth.no_role()
if not h.auth.authorized(h.auth.has_organiser_role):
if c.proposal_editing == 'closed' and not h.auth.authorized(h.auth.has_late_submitter_role):
return render("proposal/editing_closed.mako")
elif c.proposal_editing == 'not_open':
return render("proposal/editing_not_open.mako")
c.proposal = Proposal.find_by_id(id)
for key in self.form_result['proposal']:
setattr(c.proposal, key, self.form_result['proposal'][key])
c.proposal.abstract = self.clean_abstract(c.proposal.abstract)
c.person = self.form_result['person_to_edit']
if (c.person.id == h.signed_in_person().id or
h.auth.authorized(h.auth.has_organiser_role)):
for key in self.form_result['person']:
setattr(c.person, key, self.form_result['person'][key])
p_edit = "and author"
else:
p_edit = "(but not author)"
meta.Session.commit()
if Config.get('proposal_update_email') != '':
body = "Subject: %s Proposal Updated\n\nID: %d\nTitle: %s\nType: %s\nURL: %s" % (Config.get('event_name'), c.proposal.id, c.proposal.title, c.proposal.type.name.lower(), "http://" + Config.get('event_host') + h.url_for(action="view"))
email(Config.get('proposal_update_email'), body)
h.flash("Proposal %s edited!"%p_edit)
return redirect_to('/proposal')
示例3: silly_description
def silly_description():
adverb = random.choice(Config.get('silly_description', category='rego')['adverbs'])
adjective = random.choice(Config.get('silly_description', category='rego')['adjectives'])
noun = random.choice(Config.get('silly_description', category='rego')['nouns'])
start = random.choice(Config.get('silly_description', category='rego')['starts'])
if start == 'a' and adverb[0] in ['a', 'e', 'i', 'o', 'u']:
start = 'an'
desc = '%s %s %s %s' % (start, adverb, adjective, noun)
descChecksum = silly_description_checksum(desc)
return desc, descChecksum
示例4: sales_tax
def sales_tax(amount):
""" Calculate the sales tax that for the supplied amount. """
if Config.get('sales_tax_multiplier') != "":
sales_tax = int(amount * Config.get('sales_tax_multiplier'))
elif Config.get('sales_tax_divisor') != "":
sales_tax = int(amount / Config.get('sales_tax_divisor'))
else:
# wtf?
sales_tax = 0
return sales_tax
示例5: email
def email(recipients, body):
message = email_parser.Parser().parsestr(body.encode('utf-8'))
addrs = []
# Get rid of 8-bit chars in the email address fields.
for addr_header in email_addr_headers:
addrs = message.get_all(addr_header)
if not addrs or is_7bit(', '.join(addrs)):
continue
del message[addr_header]
encoded_addrs = ', '.join([encode_addr(a) for a in addrs])
message[addr_header] = encoded_addrs
# Get rid of 8-bit chars in the other message headers.
for header_name in set(message.keys()):
headers = message.get_all(header_name)
if is_7bit(''.join(headers)):
continue
del message[header_name]
for utf_header in headers:
if is_7bit(''.join(headers)):
ascii_header = utf_header
else:
ascii_header = encode_header(utf_header)
message[header_name] = ascii_header
# If the body isn't plain ascii, encode it as well.
if not message.get_charset():
email_body = message.get_payload()
if not is_7bit(email_body):
message.set_charset('utf-8')
# Default the recipients to the 'To', etc headers in the email.
if not recipients:
addrs = []
for recipient_header in recipient_addr_headers:
addrs.extend(message.get_all(recipient_header, []))
addrs = email_utils.getaddresses(addrs)
recipients = [email_utils.formataddr(a) for a in addrs]
elif type(recipients) in (str, unicode):
recipients = [recipients]
#
# If bcc_email is set, send it there as well.
#
if Config.get('bcc_email'):
recipients.append(Config.get('bcc_email'))
# send the email using smtp
try:
s = smtplib.SMTP(config['smtp_server'])
s.sendmail(Config.get('contact_email'), recipients, message.as_string())
s.quit()
except Exception as e:
h.flash(
'Unable to send email. '
'Please contact %s' % Config.get('webmaster_email'),
'error'
)
traceback.print_exc()
示例6: _redirect_user_optimally
def _redirect_user_optimally(self):
redirect_location = session.get('redirect_to', None)
if redirect_location:
del session['redirect_to']
session.save()
redirect_to(str(redirect_location))
if Config.get('conference_status') == 'open':
redirect_to(controller='registration', action='new')
elif Config.get('cfp_status') == 'open':
redirect_to(controller='proposal')
redirect_to('home')
示例7: void
def void(self, id):
if not h.auth.authorized(h.auth.Or(h.auth.is_same_zkpylons_attendee(id), h.auth.has_organiser_role)):
# Raise a no_auth error
h.auth.no_role()
c.invoice = Invoice.find_by_id(id, True)
if c.invoice.is_void:
h.flash("Invoice was already voided.")
return redirect_to(action='view', id=c.invoice.id)
elif len(c.invoice.payment_received) and h.auth.authorized(h.auth.has_organiser_role):
h.flash("Invoice has a payment applied to it, do you want to " + h.link_to('Refund', h.url_for(action='refund')) + " instead?")
return redirect_to(action='view', id=c.invoice.id)
elif len(c.invoice.payment_received):
h.flash("Cannot void a paid invoice.")
return redirect_to(action='view', id=c.invoice.id)
elif h.auth.authorized(h.auth.has_organiser_role):
c.invoice.void = "Administration Change"
meta.Session.commit()
h.flash("Invoice was voided.")
return redirect_to(action='view', id=c.invoice.id)
else:
c.invoice.void = "User cancellation"
c.person = c.invoice.person
meta.Session.commit()
email(Config.get('contact_email'), render('/invoice/user_voided.mako'))
h.flash("Previous invoice was voided.")
return redirect_to(controller='registration', action='pay', id=c.person.registration.id)
示例8: validate_python
def validate_python(self, values, state):
assertion = values['assertion']
audience = h.url_for(qualified=True, controller='home').strip("/")
page = urllib2.urlopen('https://verifier.login.persona.org/verify',
urllib.urlencode({ "assertion": assertion,
"audience": audience}))
data = json.load(page)
if data['status'] == 'okay':
c.email = data['email']
c.person = Person.find_by_email(c.email)
if c.person is None:
if not Config.get('account_creation'):
error_message = "Your sign-in details are incorrect; try the 'Forgotten your password' link below."
message = "Login failed"
error_dict = {'email_address': error_message}
raise Invalid(message, values, state, error_dict=error_dict)
# Create a new account for this email address
c.person = Person()
c.person.email_address = data['email']
c.person.activated = True
meta.Session.add(c.person)
meta.Session.commit()
if not c.person.activated:
# Persona returns verified emails only, so might as well confirm this one...
c.person.activated = True
meta.Session.commit()
示例9: photo
def photo(self, filename=None):
if not filename:
abort(404)
if "/" in filename or filename.startswith("."):
abort(403)
open_date = datetime.strptime(Config.get("date"), "%Y-%m-%dT%H:%M:%S")
days_open = (datetime.date.today() - open_date.date()).days
photo = PhotoCompEntry.from_filename(filename)
#
# If the entries haven't closed for this day then only the logged in
# person or an organiser can see it.
#
# TODO: A judge can see it too.
#
id_str = str(photo.person_id)
if days_open <= photo.day:
if not h.auth.authorized(h.auth.Or(h.auth.is_same_zkpylons_user(photo.person_id), h.auth.has_organiser_role)):
abort(403)
#
# They can have it.
#
try:
handle = open(photo.pathname(tuple(photo.scales)[0]), "rb")
except EnvironmentError, e:
if e.errno != errno.ENOENT:
raise
abort(404)
示例10: upload
def upload(self, id=None):
#
# Only an organiser can upload someone elses photos.
#
if not h.auth.authorized(h.auth.Or(h.auth.is_same_zkpylons_user(id), h.auth.has_organiser_role)):
h.auth.no_role()
open_date = datetime.strptime(Config.get("date"), "%Y-%m-%dT%H:%M:%S")
days_open = (datetime.date.today() - open_date.date()).days
photo_db = PhotoCompEntry.read_db()
if len(VALID_EXTENSIONS) == 1:
valid_extensions = VALID_EXTENSIONS[0]
else:
valid_extensions = ', '.join(VALID_EXTENSIONS[:-1]) + " or " + VALID_EXTENSIONS[-1]
#
# See what photos he has given us. The an organiser can upload
# anything without restrictions.
#
if h.auth.authorized(h.auth.has_organiser_role):
day_range = range(0, DAYS_OPEN)
else:
day_range = range(max(days_open, 0), DAYS_OPEN)
for day in day_range:
for entry_id in range(len(ENTRY_NAMES)):
old_photo = PhotoCompEntry.get(photo_db, int(id), day, entry_id)
photo_field_name = 'photo-%d-%d' % (day, entry_id)
delete_field_name = 'delete-%d-%d' % (day, entry_id)
if hasattr(request.POST[photo_field_name], 'value'):
image_data = request.POST[photo_field_name].value
image_name = request.POST[photo_field_name].filename
if len(image_data) > MAX_IMAGE_SIZE*1024*1024:
h.flash("%s is larger than %dMib" % (image_name, MAX_IMAGE_SIZE))
continue
toks = list(os.path.splitext(os.path.basename(image_name)))
if toks[0].upper() == toks[0]:
toks[0] = toks[0].lower()
toks[1] = toks[1].lower()
if not toks[1][1:] in VALID_EXTENSIONS:
h.flash("%s doesn't end in %s." % (image_name, valid_extensions))
continue
image_file = cStringIO.StringIO(image_data)
try:
image = Image.open(image_file)
image.load()
except:
h.flash("%s doesn't look like a valid image" % image_name)
continue
if image.format != "JPEG":
h.flash("%s isn't a JPEG image" % image_name)
continue
new_image_name = toks[0] + toks[1]
if old_photo:
old_photo.delete(photo_db)
new_photo = PhotoCompEntry(int(id), day, entry_id, new_image_name)
new_photo.write_orig(image_data)
new_photo.add(photo_db)
elif delete_field_name in request.POST:
if old_photo:
old_photo.delete(photo_db)
redirect_to(action="edit", id=id)
示例11: initialise_file_paths
def initialise_file_paths():
# Should be called after db is initialised
if 'enabled_theme' not in file_paths:
enabled_theme = Config.get('theme')
file_paths['enabled_theme'] = os.path.join(file_paths['theme_root'], enabled_theme)
for k in file_paths:
file_paths[k] = re.sub('\$enabled_theme', file_paths['enabled_theme'], file_paths[k])
return file_paths
示例12: __before__
def __before__(self, **kwargs):
c.funding_types = FundingType.find_all()
c.form_fields = {
'funding.why_attend': 'Why would you like to attend ' + Config.get('event_name'),
'funding.how_contribute': 'How do you contribute to the Open Source community',
'funding.male': 'What is your gender',
'funding.financial_circumstances': 'What are your financial circumstances',
}
示例13: ical
def ical(self):
c.schedule_collection = Schedule.find_all()
ical = vobject.iCalendar()
for schedule in c.schedule_collection:
if not schedule.time_slot.heading:
event = ical.add('vevent')
event.add('uid').value = str(schedule.id) + '@' + Config.get('event_host')
# Created
tz = timezone(Config.get('time_zone'))
event.add('created').value = schedule.creation_timestamp.replace(tzinfo=tz)
# Last Modified
event.add('dtstamp').value = schedule.last_modification_timestamp.replace(tzinfo=tz)
event.add('last-modified').value = schedule.last_modification_timestamp.replace(tzinfo=tz)
# Start and End Time
event.add('dtstart').value = schedule.time_slot.start_time.replace(tzinfo=tz)
event.add('dtend').value = schedule.time_slot.end_time.replace(tzinfo=tz)
# Title and Author (need to add Author here)
event.add('summary').value = schedule.event.computed_title() + '. ' + h.list_to_string(schedule.event.computed_speakers())
# Abstract, if we have one
event.add('description').value = schedule.event.computed_abstract()
# Add a URL
if schedule.event.proposal:
event.add('url').value = h.url_for(qualified=True, controller='schedule', action='view_talk', id=schedule.event.proposal.id)
elif not (schedule.event.url is None or schedule.event.url == ''):
if schedule.event.url.startswith('https://') or schedule.event.url.startswith('http://'):
event.add('url').value = h.url_for(str(schedule.event.url))
else:
event.add('url').value = h.url_for(str(schedule.event.url), qualified=True)
concurrent_schedules = schedule.event.schedule_by_time_slot(schedule.time_slot)
for concurrent_schedule in concurrent_schedules:
if concurrent_schedule != schedule:
if concurrent_schedule in c.schedule_collection:
c.schedule_collection.remove(concurrent_schedule)
locations = [concurrent_schedule.location.display_name for concurrent_schedule in concurrent_schedules]
event.add('location').value = h.list_to_string(locations)
response.charset = 'utf8'
response.headers['content-type'] = 'text/calendar; charset=utf8'
response.headers.add('content-transfer-encoding', 'binary')
response.headers.add('Pragma', 'cache')
response.headers.add('Cache-Control', 'max-age=3600,public')
return ical.serialize()
示例14: pdf
def pdf(self, id):
c.fulfilment_group = FulfilmentGroup.find_by_id(id, True)
xml_s = render('/fulfilment_group/pdf.mako')
xsl_f = app_globals.mako_lookup.get_template('/fulfilment_group/pdf.xsl').filename
pdf_data = pdfgen.generate_pdf(xml_s, xsl_f)
filename = Config.get('event_shortname') + '_' + str(c.fulfilment_group.id) + '.pdf'
return pdfgen.wrap_pdf_response(pdf_data, filename)
示例15: from_filename
def from_filename(cls, filename):
toks = filename.split("-", 4)
open_date = datetime.strptime(Config.get("date"), "%Y-%m-%dT%H:%M:%S")
photo_date = datetime.datetime(*time.strptime(toks[0], "%Y%m%d")[:3])
day = (photo_date.date() - open_date.date()).days
person_id = int(toks[1], 10)
entry_id = int(toks[2], 10)
image_name = toks[4]
photo = cls(person_id, day, entry_id, image_name)
photo.scales.add(toks[3])
return photo