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


Python models.Setting类代码示例

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


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

示例1: __setattr__

 def __setattr__(self, name, value):
     if name in ('_vals', '_name', '_appname', '_verbose_name', '_readonly', '_cache_prefix', '_main'):
         return object.__setattr__(self, name, value)
     if self._readonly:
         raise AttributeError, 'settings group %s is read-only' % self._name
     if not name in self._vals:
         raise AttributeError, 'setting "%s" not found'%name
     if not has_db:
         raise SettingsException, "no database -- settings are immutable"
     self._vals[name].initial = self._vals[name].clean(value)
     try:
         setting = Setting.objects.get(app = self._appname,
                 site = Site.objects.get_current(),
                 class_name = self._name,
                 key = name)
     except Setting.DoesNotExist:
         setting = Setting(site = Site.objects.get_current(),
                 app = self._appname,
                 class_name = self._name,
                 key = name)
     serialized = value
     if hasattr(self._vals[name].widget, '_format_value'):
         serialized = self._vals[name].widget._format_value(value)
     serialized = force_unicode(serialized)
     setting.value = serialized
     setting.save()
     if appsettings.USE_CACHE:
         cache.set(self._cache_prefix+name, value)
     if self._main:
         setattr(django_settings, name, value)
开发者ID:smacker,项目名称:django-appsettings,代码行数:30,代码来源:settingsobj.py

示例2: index

def index():
    if request.method == "GET":
        # find the latest setting record
        settings = Setting.query.order_by(desc(Setting.id)).all()
        if len(settings) > 0:
            setting = settings[0]
        else:
            setting = None
        return render_template("admin/settings.html", setting=setting)
    elif request.method == "POST":
        # get post data
        setting_id = request.form['setting_id']
        host = request.form['host']
        headline = request.form['headline']
        setting_text = request.form['text']
        start_date = request.form['start_date']
        current_app.logger.info("%s, %s, %s, %s, %s" % (setting_id, host, headline, setting_text, start_date))

        # find or create setting object
        setting = None
        if setting_id:
            setting = Setting.query.get(int(setting_id))
        if not setting:
            setting = Setting()

        # udpate db
        setting.host = host
        setting.headline = headline
        setting.setting_text = setting_text
        setting.start_date = start_date
        db_session.add(setting)
        db_session.commit()
        flash(_("Setting updated!"))
        return redirect(url_for(".index"))
开发者ID:ChinaHackers,项目名称:timeline-gallery-in-openshift,代码行数:34,代码来源:settings.py

示例3: set_value

	def set_value(self, key, value):
		setting = Setting.query.filter(Setting.key == key).first()
		if setting is None:
			setting = Setting(key,'')
			db.session.add(setting)
		# self.logger.debug('setting {0} to {1}'.format(key, value))
		setting.value = value
		db.session.commit()
开发者ID:box-community,项目名称:box-hero-report,代码行数:8,代码来源:box.py

示例4: save

 def save(self):
     """ Custom save method for standard Django Form"""
     data = self.cleaned_data
     for k,v in data.items():
         if self.user:
             Setting.set_setting(self.user, k, v)
         else:
             AdminSetting.set_setting(k, v)
开发者ID:ekaputra07,项目名称:bokerface,代码行数:8,代码来源:forms.py

示例5: create_database

def create_database(destroy_existing=False):
    """ Create db and tables if it doesn't exist """
    if not os.path.exists(DB_NAME):
        logger.info('Create database: {0}'.format(DB_NAME))
        open(DB_NAME, 'a').close()
        Show.create_table()
        Episode.create_table()
        Setting.create_table()
开发者ID:tax,项目名称:snor,代码行数:8,代码来源:utils.py

示例6: playlist_content_html

def playlist_content_html():
    """" Returns the HTML for the structure of the playlists as they will be
    populated ont he homepage. Does not actually contain the list of video
    names as those are filled in later asynchronously via the cache.
    
    """
    
    # No cache found -- regenerate HTML
    smart_history = getSmartHistoryContent()

    dict_playlists_by_title = {}
    all_playlists = []

    for playlist in Playlist.all():
        if playlist.title in topics_list:
            dict_playlists_by_title[playlist.title] = playlist

    for topic in topics_list:
        if topic in dict_playlists_by_title:
            playlist = dict_playlists_by_title[topic]
            video_count = playlist.get_video_count() 
            # 3 columns, 18px per row. This must be updated in conjunction
            # with code in homepage.js
            height = math.ceil(video_count / 3) * 18

            playlist_data = {
                             'title': topic,
                             'topic': topic,
                             'playlist': playlist,
                             'list_height': height,
                             'next': None,
                             }

            all_playlists.append(playlist_data)

    playlist_data_prev = None
    for playlist_data in all_playlists:
        if playlist_data_prev:
            playlist_data_prev['next'] = playlist_data
        playlist_data_prev = playlist_data

    timestamp = time.time()
    template_values = {
        'App' : App,
        'all_playlists': all_playlists,
        'smart_history': smart_history,
        
        # convert timestamp to a nice integer for the JS
        'timestamp': int(round(timestamp * 1000)),
        }

    html = shared_jinja.get().render_template("library_playlist_template.html",
                                              **template_values)
    Setting.cached_playlist_content_date(
            str(datetime.datetime.fromtimestamp(timestamp)))
    return html
开发者ID:KhanWorld,项目名称:KhanAcademy,代码行数:56,代码来源:library.py

示例7: get_settings

 def get_settings(self):
     try:
         setting = Setting.get(name=self.setting_name)
         return json.loads(setting.value)
     except:
         Setting.create(
             name=self.setting_name,
             value=json.dumps(self._settings)
         )
     return self._settings
开发者ID:tax,项目名称:snor,代码行数:10,代码来源:conf.py

示例8: load_deeds

    def load_deeds(self):
        if not Setting.get('user_id', None):
            self.set_status("Error: Please set user_id and password in settings")
            return

        sync.load_sync_data(
            Setting.get_all(self.db),
            on_success=self.sync_load_success,
            on_error=self.sync_error,
            on_failure=self.sync_error
            )
开发者ID:kashifpk,项目名称:GoodOrBad,代码行数:11,代码来源:good_or_bad.py

示例9: sync_deeds

 def sync_deeds(self):
     if not Setting.get('user_id', None):
         self.set_status("Error: Please set user_id and password in settings")
         return 
     
     sync.sync_data(
         self.db.query(Deed).filter_by(synced=False),
         Setting.get_all(self.db),
         on_success=self.sync_success,
         on_error=self.sync_error,
         on_failure=self.sync_error
         )
开发者ID:kashifpk,项目名称:GoodOrBad,代码行数:12,代码来源:good_or_bad.py

示例10: set_settings

 def set_settings(self, **kwargs):
     # Only copy valid keys fallback to default settings
     vk = self._settings.keys()
     kwargs = {k: v for k, v in kwargs.items() if k in vk}
     kwargs = dict(self._settings.items() + kwargs.items())
     try:
         s = Setting.get(name=self.setting_name)
         s.value = json.dumps(kwargs)
         s.save()
     except:
         Setting.create(
             name=self.setting_name,
             value=json.dumps(kwargs),
             date_last_updated=datetime.datetime.now()
         )
开发者ID:tax,项目名称:snor,代码行数:15,代码来源:conf.py

示例11: test_setting_unicode

    def test_setting_unicode(self):
        a = Setting.get('test')

        self.assertEqual(a.__unicode__(), 'test')

        a.set_value('e')
        self.assertEqual(a.get_value(), 'e')
开发者ID:PopAdi,项目名称:wouso,代码行数:7,代码来源:tests.py

示例12: post

    def post(self):
        if bool(self.request.get('choice')):
            ndb.delete_multi(Student.query().fetch(keys_only=True))
            ndb.delete_multi(Assignment.query().fetch(keys_only=True))
            ndb.delete_multi(Setting.query().fetch(keys_only=True))

        self.redirect('/admin')
开发者ID:austinsherron,项目名称:partner_app,代码行数:7,代码来源:admin_misc.py

示例13: create_app

def create_app(config):
    if config is None:
        config = 'dev'
    if not os.path.isfile(CONFIG_FILE):
        create_config()
    #Create Flask application
    app = Flask(__name__)
    app.config.from_object(configurations[config])

    #set 404 errors to the not_found function
    app.error_handler_spec[None][404] = not_found

    #Init flask extentinons
    db.init_app(app)
    with app.app_context():
        from models import Setting
        try:
            db_version = Setting.db_version()
            if db_version < Setting.DB_VERSION:
                #TODO: Implement settings db upgrade code
                print " * Upgrading the settings database"
        except:
            pass
    
    from .api_v1 import api_v1
    app.register_blueprint(api_v1)

    return app
开发者ID:SweBarre,项目名称:sciurus,代码行数:28,代码来源:__init__.py

示例14: post

    def post(self):
        # Protected for admins only by app.yaml so taskqueue can hit this URL
        step = self.request_int("step", default = 0)

        if step == YouTubeSyncStep.START:
            self.startYouTubeSync()
        elif step == YouTubeSyncStep.UPDATE_VIDEO_AND_PLAYLIST_DATA:
            self.updateVideoAndPlaylistData()
#        elif step == YouTubeSyncStep.UPDATE_VIDEO_AND_PLAYLIST_READABLE_NAMES:
#            self.updateVideoAndPlaylistReadableNames()
#        elif step == YouTubeSyncStep.COMMIT_LIVE_ASSOCIATIONS:
#            self.commitLiveAssociations()
#        elif step == YouTubeSyncStep.INDEX_VIDEO_DATA:
#            self.indexVideoData()
#        elif step == YouTubeSyncStep.INDEX_PLAYLIST_DATA:
#            self.indexPlaylistData()
#        elif step == YouTubeSyncStep.REGENERATE_LIBRARY_CONTENT:
#            self.regenerateLibraryContent()
        elif step == YouTubeSyncStep.UPDATE_FROM_TOPICS:
            self.copyTopicsToPlaylist()

        log = YouTubeSyncStepLog()
        log.step = step
        log.generation = int(Setting.last_youtube_sync_generation_start())
        log.put()

        if step < YouTubeSyncStep.UPDATE_FROM_TOPICS:
            self.task_step(step + 1)
开发者ID:johnfelipe,项目名称:server,代码行数:28,代码来源:youtube_sync.py

示例15: update_database

def update_database():
	last_data = {'readings':{'temp':0,'humidity':0}, 'parameters':None}
	while 1:
		update_time = timezone.now()
		data = (yield)
		if (round(last_data["readings"]["temp"]) != round(data["readings"]["temp"])) or (round(last_data["readings"]["humidity"]) != round(data["readings"]["humidity"])):
			try:
				reading_record = Reading.objects.get(pk=1)
			except Reading.DoesNotExist:
				reading_record = Reading(time=update_time, temperature=data["readings"]["temp"], humidity=data["readings"]["humidity"])
			else:
				reading_record.time = update_time
				reading_record.temperature = data["readings"]["temp"]
				reading_record.humidity = data["readings"]["humidity"]
			reading_record.save()
		if last_data["parameters"] != data["parameters"]:
			setting_record = Setting(time=update_time, mode=data["parameters"]["mode"], temperature=data["parameters"]["temp"], humidity=data["parameters"]["humidity"])
			setting_record.save()
		last_data = data
开发者ID:daniel2078,项目名称:Climaduino-web-controller,代码行数:19,代码来源:climaduino_controller_mock.py


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