当前位置: 首页>>代码示例>>Python>>正文


Python config.get函数代码示例

本文整理汇总了Python中tg.config.get函数的典型用法代码示例。如果您正苦于以下问题:Python get函数的具体用法?Python get怎么用?Python get使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了get函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: sendmail

def sendmail(to_addrs, subject, text):

    server = config.get('smtp_server')
    use_tls = asbool(config.get('smtp_use_tls'))
    username = config.get('smtp_username')
    password = config.get('smtp_password')
    from_addr = config.get('admin_email_from')

    log.debug('Sending mail via %s' % server)

    if use_tls:
        s = SMTP_SSL()
    else:
        s = SMTP()
    s.connect(server)
    if username:
        s.login(username, password)
    msg = MIMEText(text, _charset='utf-8')
    msg['From'] = from_addr
    msg['Reply-To'] = from_addr
    if isinstance(to_addrs, basestring):
        msg['To'] = to_addrs
    else:
        msg['To'] = ', '.join(to_addrs)
    msg['Subject'] = subject
    s.sendmail(from_addr, to_addrs, msg.as_string())
    s.quit()
开发者ID:samsemilia7,项目名称:SAUCE,代码行数:27,代码来源:mail.py

示例2: __call__

 def __call__(self):
     
     lang = init_lang()
     
     vars_ = dict(display_name=self.u.display_name,
                  user_name=self.u.user_name,
                  new_password=self.new_password,
                  app_title=config.get('mail.name').decode('utf-8'),
                  )
     
     asunto = self.env.get_template('sapns/users/forgot_password/%s/subject.txt' % lang)
     asunto = asunto.render(**vars_).encode('utf-8')
     
     mensaje = self.env.get_template('sapns/users/forgot_password/%s/message.txt' % lang)
     mensaje = mensaje.render(**vars_).encode('utf-8')
     
     mensaje_html = self.env.get_template('sapns/users/forgot_password/%s/message.html' % lang)
     mensaje_html = mensaje_html.render(**vars_).encode('utf-8')
     
     email_login = config.get('mail.user')
     email_password = config.get('mail.password')
     
     # send e-mail
     send_mail(self.remitente, self.dst, asunto, mensaje,
               config.get('mail.smtp'), email_login, email_password, 
               html=mensaje_html)
开发者ID:leondomingo,项目名称:Sapns,代码行数:26,代码来源:forgot_password.py

示例3: load_results_page

    def load_results_page(self, beg_date, end_date):
        log.debug("Trying to load page 1 of ??")

        # Login page
        # TODO -- there are about 6 other counties we can scrape here.
        url = '%s/NY-Monroe/' % self.base
        self.browser.open(url)
        self.browser.follow_link(url_regex=re.compile('.*loginForm.*'))
        self.browser.select_form(nr=0)
        self.browser.form['txtUserName'] = config.get('propertyinfo.username')
        self.browser.form['txtPassword'] = config.get('propertyinfo.password')
        self.browser.submit()

        # Load search page and input criteria
        self.browser.follow_link(url_regex=re.compile('.*=2004.*'))
        self.browser.select_form(name='frmSavedCriteria')
        self.set_hidden_form_value('SearchbyDateFrom', beg_date)
        self.set_hidden_form_value('SearchbyDateTo', end_date)
        # TODO -- there are lots of other doc types we can get here.
        self.set_hidden_form_value('SearchDocType',
                              "NOTICE OF PENDENCY MORTGAGE FORECLOSURE")
        self.browser.form.action = '%s/wam3/SearchSummary.asp' % self.apps_base
        self.browser.submit()

        # Follow an implicit redirect
        try:
            # which, however, will shit the bed if there are no results
            self.browser.select_form(name='frmResult')
            self.browser.submit()
        except mechanize._mechanize.FormNotFoundError:
            log.debug("No results found for %s to %s" % (beg_date, end_date))
            return None
开发者ID:wevecometotakethemback,项目名称:monroe,代码行数:32,代码来源:propertyinfo.py

示例4: _toPrintshop

 def _toPrintshop( self, hdr, subject, content, files = [] ):
     defaultsendto = config.get( "default_email_sendto", "" ).split( ";" )
     if hdr.printShopId and hdr.printShop.email: to = hdr.printShop.email
     else: to = []
     sendto = defaultsendto + to
     cc = config.get( "default_email_cc", "" ).split( ";" )
     if config.get( "sendout_email", None ) != 'F': sendEmail( DEFAULT_SENDER, sendto, subject, '\n'.join( content ), cc, files )
开发者ID:LamCiuLoeng,项目名称:aeo,代码行数:7,代码来源:ordering.py

示例5: _toVendor

 def _toVendor( self, hdr , subject, content, files = [] ):
     defaultsendto = config.get( "default_email_sendto", "" ).split( ";" )
     if hdr.createBy.email_address:  to = hdr.createBy.email_address.split( ";" )
     else: to = []
     sendto = defaultsendto + to
     cc = config.get( "default_email_cc", "" ).split( ";" )
     if config.get( "sendout_email", None ) != 'F': sendEmail( DEFAULT_SENDER, sendto, subject, '\n'.join( content ), cc, files )
开发者ID:LamCiuLoeng,项目名称:aeo,代码行数:7,代码来源:ordering.py

示例6: production_export

    def production_export( self, **kw ):
        ws = [Item.active == 0, Item.status == STATUS_APPROVE, ]
        if kw.get( "jobNo", False ) : ws.append( Item.jobNo.op( "ilike" )( "%%%s%%" % kw["jobNo"] ) )
        if kw.get( "systemNo", False ) : ws.append( Item.systemNo.op( "ilike" )( "%%%s%%" % kw["systemNo"] ) )
        if kw.get( "desc", False ) : ws.append( Item.desc.op( "ilike" )( "%%%s%%" % kw["desc"] ) )
        if kw.get( "approve_time_from", False ) : ws.append( Item.approveTime >= kw["approve_time_from"] )
        if kw.get( "approve_time_to", False ) : ws.append( Item.approveTime <= kw["approve_time_to"] )
        result = qry( Item ).filter( and_( *ws ) ).order_by( desc( Item.createTime ) ).all()

        data = []
        for h in  qry( Item ).filter( and_( *ws ) ).order_by( desc( Item.createTime ) ):
            data.append( map( unicode, [ h.systemNo, h.jobNo, h.desc, h.createTime.strftime( "%Y/%m/%d %H:%M" ),
                                      h.showStatus(),
                                      h.approveTime.strftime( "%Y/%m/%d %H:%M" ) if h.approveTime else '',
                                     ] ) )

        try:
            v = getExcelVersion()
            if not v : raise ReportGenerationException()
            if v <= "2003" :  # version below 2003
                templatePath = os.path.join( config.get( "public_dir" ), "TEMPLATE", "CAB_PRODUCTION_REPORT_TEMPLATE.xls" )
            else :  # version above 2003
                templatePath = os.path.join( config.get( "public_dir" ), "TEMPLATE", "CAB_PRODUCTION_REPORT_TEMPLATE.xlsx" )

            tempFileName, realFileName = self._getReportFilePath( templatePath )
            sdexcel = CABItemReport( templatePath = tempFileName, destinationPath = realFileName )
            sdexcel.inputData( data )
            sdexcel.outputData()
        except:
            traceback.print_exc()
            logError()
            if sdexcel:sdexcel.clearData()
            raise ReportGenerationException()
        else:
            return serveFile( realFileName )
开发者ID:LamCiuLoeng,项目名称:cabelas,代码行数:35,代码来源:logic.py

示例7: _generator

        def _generator():
            while True:
                from pymongo import MongoClient
                from tg import config
                client = MongoClient("%s%s" % (config.get('ming.url'), config.get('ming.db')))
                db = client.spacehackaton
                '''
                data_to_deactivate = db.node.find(
                    {
                        'update_time': {
                            '$lt': datetime.datetime.utcnow()-datetime.timedelta(seconds=10)
                        }
                    }
                )

                for item_to_deactivate in data_to_deactivate:
                    db.node.update({'name': item_to_deactivate.get('name')}, {'$set': {'status': 'INACTIVE'}})
                '''
                data_to_return = db.node.find()
                json_data = json.dumps([self.to_json(x) for x in data_to_return], sort_keys=True, indent=4,
                                       default=json_util.default)
                event = "data: %s\n\n" % json.loads(json_data)
                sleep(1)
                #print "Nodes", event.replace("u'", "'").replace("'", "\"")
                client.close()
                yield event.replace("u'", "'").replace("'", "\"").encode('utf-8')
开发者ID:finch20046,项目名称:spacehackaton,代码行数:26,代码来源:api_controller.py

示例8: _plain_send_mail

def _plain_send_mail(sender, recipient, subject, body):
    header_charset = 'ISO-8859-1'
    for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
        try:
            body.encode(body_charset)
        except UnicodeError:
            pass
        else:
            break

    sender_name, sender_addr = parseaddr(sender)
    recipient_name, recipient_addr = parseaddr(recipient)

    sender_name = str(Header(unicode(sender_name), header_charset))
    recipient_name = str(Header(unicode(recipient_name), header_charset))

    sender_addr = sender_addr.encode('ascii')
    recipient_addr = recipient_addr.encode('ascii')

    msg = MIMEText(body.encode(body_charset), 'plain', body_charset)
    msg['From'] = formataddr((sender_name, sender_addr))
    msg['To'] = formataddr((recipient_name, recipient_addr))
    msg['Subject'] = Header(unicode(subject), header_charset)

    smtp = SMTP(config.get('registration.smtp_host', 'localhost'))
    if config.get('registration.smtp_login'):
        try:
            smtp.starttls()
        except:
            pass
        smtp.login(config.get('registration.smtp_login'), config.get('registration.smtp_passwd'))
    smtp.sendmail(sender, recipient, msg.as_string())
    smtp.quit()
开发者ID:mbbui,项目名称:Jminee,代码行数:33,代码来源:__init__.py

示例9: recover_user_password

def recover_user_password(user):
    key = user.generate_recover_key(request.remote_addr)

    text = u"""Hi %s,

you have asked to recover your password (from IP %s).  To enter a new
password, click on the following link:

 http://skylines.xcsoar.org/users/recover?key=%x

The SkyLines Team
""" % (unicode(user), request.remote_addr, key)

    msg = email.mime.text.MIMEText(text.encode('utf-8'), 'plain', 'utf-8')
    msg['Subject'] = 'SkyLines password recovery'
    msg['From'] = config.get('email_from', '[email protected]')
    msg['To'] = user.email_address.encode('ascii')
    msg['Date'] = email.Utils.formatdate(localtime=1)

    try:
        smtp = smtplib.SMTP(config.get('smtp_server', 'localhost'))
        smtp.ehlo()
        smtp.sendmail(config.get('email_from', '[email protected]').encode('ascii'),
                      user.email_address.encode('ascii'), msg.as_string())
        smtp.quit()
    except:
        raise HTTPServiceUnavailable(explanation=_(
            "The mail server is currently not reachable. "
            "Please try again later or contact the developers."))
开发者ID:citterio,项目名称:Skylines,代码行数:29,代码来源:users.py

示例10: command

    def command(self):
        config=load_config(self.args)
        if self.options.export:
            f = open(config.get('starlogic.out'),'w')
            fs = open(config.get('starlogic.sincro'))
            sincro = 0
            for i in  fs.readlines():
                sincro = i.strip()
                sincro = int(sincro)
            fs.close()
            ps = DBSession.query(Eanprodotti)
            if not self.options.all:
                ps = ps.filter(Eanprodotti.sincrofield>sincro)
            ps = ps.order_by(Eanprodotti.sincrofield).all()

            for p in ps:
                codart = p.prodotto.eans[0].ean
                desc = p.prodotto.prodotto.encode('ascii', 'ignore')
                prezzo = p.prodotto.prezzo            
                sincro = p.sincrofield
                print >> f, "%s;%s;%s;%s;%s"%(codart, p.ean, desc, prezzo,0)
                
                if len(p.aliases)>0:
                    for alias in p.aliases:
                        print >> f, "%s;%s;%s;%s;%s"%(codart, alias.alias, desc, prezzo,1)
            f.close()
            f = open(config.get('starlogic.sincro'),'w')
            print >>  f, sincro		        
            f.close()
开发者ID:nomed,项目名称:ebetl,代码行数:29,代码来源:starlogic.py

示例11: zarkov_event

    def zarkov_event(self, event_type, user=None, neighborhood=None, project=None, app=None, extra=None):
        context = dict(user=None, neighborhood=None, project=None, tool=None, mount_point=None, is_project_member=False)

        if not config.get("zarkov.host"):
            return

        user = user or getattr(c, "user", None)
        project = project or getattr(c, "project", None)
        app = app or getattr(c, "app", None)
        if user:
            context["user"] = user.username
        if project:
            context.update(project=project.shortname, neighborhood=project.neighborhood.url_prefix.strip("/"))
            if user:
                cred = Credentials.get()
                if cred is not None:
                    for pr in cred.user_roles(user._id, project._id).reaching_roles:
                        if pr.get("name") and pr.get("name")[0] != "*":
                            context["is_project_member"] = True
        if app:
            context.update(tool=app.config.tool_name, mount_point=app.config.options.mount_point)

        try:
            if self._zarkov is None:
                self._zarkov = ZarkovClient(config.get("zarkov.host", "tcp://127.0.0.1:6543"))
            self._zarkov.event(event_type, context, extra)
        except Exception, ex:
            self._zarkov = None
            log.error("Error sending zarkov event(%r): %r", ex, dict(type=event_type, context=context, extra=extra))
开发者ID:apache,项目名称:incubator-allura,代码行数:29,代码来源:app_globals.py

示例12: export

def export(page, plugins_data):
    buf = StringIO()
    quoting = config.get('csv_quoting', 'ALL').upper()
    if quoting not in ('ALL', 'MINIMAL', 'NONNUMERIC', 'NONE'):
        quoting = 'ALL'
    csv_writer = csv.DictWriter(buf,
        config['csv_columns'],
        extrasaction='ignore',
        delimiter=config.get("csv_delimiter_char", ';'),
        escapechar=config.get("csv_escape_char", '\\'),
        quotechar=config.get("csv_quote_char", '"'),
        quoting=getattr(csv, 'QUOTE_%s' % quoting))
    csv_writer.writerow(dict(zip(config['csv_columns'], config['csv_columns'])))

    for item in page.items:
        values = {}
        for plugin_name, plugin_instance in config['columns_plugins']:
            if plugins_data[plugin_name]:
                values[plugin_name] = repr(plugins_data[plugin_name])
            else:
                for data_key, data_value in \
                    plugin_instance.get_data(item).iteritems():
                    # Pour les valeurs en unicode, on convertit en UTF-8.
                    if isinstance(data_value, unicode):
                        values[data_key] = data_value.encode('utf-8')
                    # Pour le reste, on suppose qu'on peut en obtenir une
                    # représentation adéquate dont l'encodage ne posera pas
                    # de problème.
                    else:
                        values[data_key] = data_value
        csv_writer.writerow(values)
    return buf.getvalue()
开发者ID:vigilo,项目名称:vigiboard,代码行数:32,代码来源:export_csv.py

示例13: nav_logo

    def nav_logo(self):
        logo = dict(
            redirect_link=config.get('logo.link', False),
            image_path=config.get('logo.path', False),
            image_width=config.get('logo.width', False),
            image_height=config.get('logo.height', False)
        )
        if not logo['redirect_link']:
            logo['redirect_link'] = '/'

        if not logo['image_path']:
            log.warning('Image path not set for nav_logo')
            return False

        allura_path = os.path.dirname(os.path.dirname(__file__))
        image_full_path = '%s/public/nf/images/%s' % (
            allura_path, logo['image_path'])

        if not os.path.isfile(image_full_path):
            log.warning('Could not find logo at: %s' % image_full_path)
            return False

        path = 'images/%s' % logo['image_path']
        return {
            "image_path": self.forge_static(path),
            "redirect_link": logo['redirect_link'],
            "image_width": logo['image_width'],
            "image_height": logo['image_height']
        }
开发者ID:heiths,项目名称:allura,代码行数:29,代码来源:app_globals.py

示例14: after_init_config

    def after_init_config(self):

        from tg import config as tgconf

        if tgconf.get('debug', False):
            # Always show warnings for the sauce module
            import warnings
            warnings.filterwarnings(action='once', module='sauce')
            warnings.filterwarnings(action='once', module='.*mak')

        _locale = tgconf.get('locale')

        try:
            locale.setlocale(locale.LC_ALL, _locale)
        except Exception:  # pragma: no cover
            log.exception('Could not set locale: %s', _locale)
        else:
            log.debug('Locale set to: %s', _locale)

        for fmt in ('D_FMT', 'T_FMT', 'D_T_FMT'):
            fmtstr = tgconf.get(fmt, None)
            if fmtstr:
                # Self-baked %-escaping
                fmtstr = fmtstr.replace('%%', '%')
            if not fmtstr:
                fmtstr = locale.nl_langinfo(getattr(locale, fmt))
                log.debug('Format string for %s read from locale: %s', (fmt, fmtstr))
            setattr(tgconf, fmt, fmtstr)
开发者ID:Ayutac,项目名称:SAUCE,代码行数:28,代码来源:app_cfg.py

示例15: __init__

    def __init__(self, *args, **kw):
        super(ChatController, self).__init__(*args, **kw)
        self.config = {}
        backend = config.get('chat.backend')
        if not backend:
            log.info('No `chat.backend` defined; disabling chat functionality')
            return
        backend = urlparse.urlparse(backend)
        if hasattr(backend, 'scheme'): # Python 2.5+
            self.config['backendProtocol'] = backend.scheme
            self.config['backendAddr'] = [backend.hostname, backend.port]
        else: # Python 2.4
            self.config['backendProtocol'] = backend[0]
            host, port = backend[1].split(':')
            self.config['backendAddr'] = [host, port]
        self.config['startBuiltin'] = config.get('chat.builtin', False)
        self.config['rooms'] = {}
        display_opts = {
                'floating': True, 'floatingToggle': False, 'width': 400 ,
                'height': 300, 'theme': 'simple', 'resizable': True,
                'greeting': 'Moksha Chat',
                }
        for room in config['chat.rooms'].replace(',', ' ').split():
            self.config['rooms'][room] = {'display': {}}
            for display_opt, default in display_opts.items():
                self.config['rooms'][room]['display'][display_opt] = \
                        config.get('chat.%s.display.%s' % (room, display_opt),
                                   default)
            self.config['rooms'][room]['roomAssignmentMode'] = \
                    config.get('chat.%s.roomAssignmentMode' % room, 'static')
            self.config['rooms'][room]['staticRoomName'] = \
                    config.get('chat.%s.staticRoomName' % room, room)

        log.debug('Chat config = %r' % self.config)
开发者ID:lmacken,项目名称:moksha,代码行数:34,代码来源:chat.py


注:本文中的tg.config.get函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。