def AramaYap(self, obj): x_forwarded_for = self.request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: IP = x_forwarded_for.split(',')[0] else: IP = self.request.META.get('REMOTE_ADDR') SANTRAL_SABIT_IP = settings.__getattr__('SANTRAL_SABIT_IP') SANTRAL_IP = settings.__getattr__('SANTRAL_IP') SANTRAL_DAHILI = settings.__getattr__('SANTRAL_DAHILI') SANTRAL_PORT = settings.__getattr__('SANTRAL_PORT') SANTRAL_CLICK2CALL = settings.__getattr__('SANTRAL_CLICK2CALL') # "/Services/callservice.aspx?username=click2call&password=cl12sprtf&exten=&phone=" if str(str(self.request.user).split('_')[0]).isdigit(): Dahili = str(str(self.request.user).split('_')[0]) else: Dahili = SANTRAL_DAHILI if obj.Telefon and IP == SANTRAL_SABIT_IP: # # Aynı IP kullanılıyorsa yani şirket içinde ise gibi return u"<a target='_blank' href='http://" + SANTRAL_IP + ":" + SANTRAL_PORT + SANTRAL_CLICK2CALL + Dahili + "&phone=" + str( obj.Telefon).replace(' ', '') + u"'> Ara </a>" else: return u"<a target='_blank' href='http://" + SANTRAL_SABIT_IP + ":" + SANTRAL_PORT + SANTRAL_CLICK2CALL + Dahili + "&phone=" + str( obj.Telefon).replace(' ', '') + u"'> Ara </a>"
def __getattr__(self, name): try: if isinstance(microsite.get_value(name), dict): return microsite.get_dict(name, base_settings.__getattr__(name)) return microsite.get_value(name, base_settings.__getattr__(name)) except KeyError: base_settings.__getattr__(name)
def __init__(self, queue, callback, port=5672): self._mq_credentials_user = settings.__getattr__('MQ_CREDENTIAL_USER') self._mq_credentials_password = settings.__getattr__( 'MQ_CREDENTIAL_PASSWORD') self._mq_host = settings.__getattr__('MQ_HOST') self._queue = queue self._callback = callback if port is not None: self._mq_port = port else: self._mq_port = 5672 if self._callback is None: raise Exception('call back is required') try: self._credentials = pika.PlainCredentials( self._mq_credentials_user, self._mq_credentials_password) self._connection = pika.BlockingConnection( pika.ConnectionParameters(self._mq_host, self._mq_port, '/', self._credentials)) self._channel = self._connection.channel() logger.info('{} chanel初始化成功'.format(self._queue)) except Exception as e: logger.error('{} chanel初始化失败,失败原因{}'.format( self._queue, e.message)) raise Exception('{}{}chanel初始化失败,失败原因{}'.format( self._queue, e.message))
def AramaYap(self, obj): x_forwarded_for = self.request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: IP = x_forwarded_for.split(',')[0] else: IP = self.request.META.get('REMOTE_ADDR') SANTRAL_SABIT_IP = settings.__getattr__('SANTRAL_SABIT_IP') SANTRAL_IP = settings.__getattr__('SANTRAL_IP') SANTRAL_DAHILI = settings.__getattr__('SANTRAL_DAHILI') SANTRAL_PORT = settings.__getattr__('SANTRAL_PORT') SANTRAL_CLICK2CALL = settings.__getattr__('SANTRAL_CLICK2CALL') uyetelefon = Kullanicilar.objects.get(uyeid=obj.UyeID).uyetelefon if str(str(self.request.user).split('_')[0]).isdigit(): Dahili = str(str(self.request.user).split('_')[0]) else: Dahili = SANTRAL_DAHILI if uyetelefon and IP == SANTRAL_SABIT_IP: # # Aynı IP kullanılıyorsa yani şirket içinde ise gibi return u"<a target='_blank' href='http://" + SANTRAL_IP + ":" + SANTRAL_PORT + SANTRAL_CLICK2CALL + Dahili + "&phone=" + str( uyetelefon).replace(' ', '') + u"'> Ara </a>" else: return u"<a target='_blank' href='http://" + SANTRAL_SABIT_IP + ":" + SANTRAL_PORT + SANTRAL_CLICK2CALL + Dahili + "&phone=" + str( uyetelefon).replace(' ', '') + u"'> Ara </a>"
def get_settings(name, key=None): """""" if not key: return settings.__getattr__(name) else: dictionary = settings.__getattr__(name) return dictionary[key]
def __contains__(self, name): if not self._is_loaded: raise Exception("settings have not been loaded") if name in self._local_settings: return True try: django_settings.__getattr__(name) return True except: return False
def __init__(self): self.ftp_host = settings.__getattr__('FTP_HOST') self.ftp_port = settings.__getattr__('FTP_PORT') self.ftp_user = settings.__getattr__('FTP_USER') self.ftp_password = settings.__getattr__('FTP_PASSWORD') try: self._connect = ftplib.FTP(host=self.ftp_host, user=self.ftp_user, passwd=self.ftp_password) except Exception as e: raise Exception(e.message)
def queryset(self, request, queryset): urun_listesiii = () if self.value() == 'ns': for i in queryset.annotate( ToplamStok_Sayisi=Sum('varyant__StokSayisi')).filter( ToplamStok_Sayisi__gt=settings.__getattr__( 'NORMAL_STOK')).order_by('-id'): if FotoKontrol(i.Logo): urun_listesiii += (str(Urun.objects.get(id=i.id).id), ) elif self.value() == 'ks': for i in queryset.annotate( ToplamStok_Sayisi=Sum('varyant__StokSayisi')).filter( ToplamStok_Sayisi__gt=settings.__getattr__( 'KRITIK_STOK'), ToplamStok_Sayisi__lt=settings.__getattr__( 'NORMAL_STOK')).order_by('-id'): if FotoKontrol(i.Logo): urun_listesiii += (str(Urun.objects.get(id=i.id).id), ) elif self.value() == 'fs': for i in queryset.annotate( ToplamStok_Sayisi=Sum('varyant__StokSayisi')).filter( ToplamStok_Sayisi__gt=settings.__getattr__( 'FAZLA_STOK')).order_by('-id'): if FotoKontrol(i.Logo): urun_listesiii += (str(Urun.objects.get(id=i.id).id), ) elif self.value() == 'ts': for i in queryset.annotate( ToplamStok_Sayisi=Sum('varyant__StokSayisi')).filter( ToplamStok_Sayisi=0).order_by('-id'): if FotoKontrol(i.Logo): urun_listesiii += (str(Urun.objects.get(id=i.id).id), ) elif self.value() == "hs": for i in queryset.annotate( ToplamStok_Sayisi=Sum('varyant__StokSayisi')).filter( ToplamStok_Sayisi=None).order_by('-id'): if FotoKontrol(i.Logo): urun_listesiii += (str(Urun.objects.get(id=i.id).id), ) else: for i in queryset.annotate( ToplamStok_Sayisi=Sum('varyant__StokSayisi')).filter( ToplamStok_Sayisi__gt=0).order_by('-id'): urun_listesiii += (str(Urun.objects.get(id=i.id).id), ) return queryset.filter(id__in=urun_listesiii)
def del_midia_filer(file_name): for root, dirs, files in os.walk(settings.__getattr__('FILER_PUBLIC'), topdown=False): for name in files: if name.startswith(file_name.lower()): dad_path, midia = os.path.split(os.path.join(root, name)) os.remove(os.path.join(root, name)) # del_recursive_folder(dad_path) for root, dirs, files in os.walk(settings.__getattr__('FILER_PUBLIC_THUMBNAIL'), topdown=False): for name in files: if name.startswith(file_name.lower()): dad_path, midia = os.path.split(os.path.join(root, name)) os.remove(os.path.join(root, name)) # del_recursive_folder_thumbnails(dad_path)
def settings(name): """Display settings on template Usage: {% settings 'DEBUG' %} """ return str(_settings.__getattr__(name))
def update_defaults(self): """ We make sure to store the most important object defaults here, so we can catch if they change and update them on-objects automatically. This allows for changing default cmdset locations and default typeclasses in the settings file and have them auto-update all already existing objects. """ # setting names settings_names = ( "CMDSET_CHARACTER", "CMDSET_PLAYER", "BASE_PLAYER_TYPECLASS", "BASE_OBJECT_TYPECLASS", "BASE_CHARACTER_TYPECLASS", "BASE_ROOM_TYPECLASS", "BASE_EXIT_TYPECLASS", "BASE_SCRIPT_TYPECLASS", "BASE_CHANNEL_TYPECLASS", ) # get previous and current settings so they can be compared settings_compare = zip( [ServerConfig.objects.conf(name) for name in settings_names], [settings.__getattr__(name) for name in settings_names], ) mismatches = [i for i, tup in enumerate(settings_compare) if tup[0] and tup[1] and tup[0] != tup[1]] if len(mismatches): # can't use any() since mismatches may be [0] which reads as False for any() # we have a changed default. Import relevant objects and # run the update from evennia.objects.models import ObjectDB from evennia.comms.models import ChannelDB # from evennia.players.models import PlayerDB for i, prev, curr in ((i, tup[0], tup[1]) for i, tup in enumerate(settings_compare) if i in mismatches): # update the database print( " %s:\n '%s' changed to '%s'. Updating unchanged entries in database ..." % (settings_names[i], prev, curr) ) if i == 0: ObjectDB.objects.filter(db_cmdset_storage__exact=prev).update(db_cmdset_storage=curr) if i == 1: PlayerDB.objects.filter(db_cmdset_storage__exact=prev).update(db_cmdset_storage=curr) if i == 2: PlayerDB.objects.filter(db_typeclass_path__exact=prev).update(db_typeclass_path=curr) if i in (3, 4, 5, 6): ObjectDB.objects.filter(db_typeclass_path__exact=prev).update(db_typeclass_path=curr) if i == 7: ScriptDB.objects.filter(db_typeclass_path__exact=prev).update(db_typeclass_path=curr) if i == 8: ChannelDB.objects.filter(db_typeclass_path__exact=prev).update(db_typeclass_path=curr) # store the new default and clean caches ServerConfig.objects.conf(settings_names[i], curr) ObjectDB.flush_instance_cache() PlayerDB.flush_instance_cache() ScriptDB.flush_instance_cache() ChannelDB.flush_instance_cache() # if this is the first start we might not have a "previous" # setup saved. Store it now. [ServerConfig.objects.conf(settings_names[i], tup[1]) for i, tup in enumerate(settings_compare) if not tup[0]]
def reset_pwd(request): username = request.POST.get('username') email = request.POST.get('email') user = UserInfo.objects.filter(username=username) if not user: return JsonResponse({"status": "faild", "code": 500, "msg": "用户名不存在"}) if email != user.values('email')[0]['email']: return JsonResponse({"status": "faild", "code": 500, "msg": "邮箱地址不正确"}) new_password = get_random_string_from_random(8) UserInfo.objects.set_passwd(username, new_password) subject = "应用管理系统-密码找回--{}".format(settings.__getattr__('EMAIL_ENV')) context = ''' <html> <meta charset="utf-8"> <body> <p style="margin-left: 20px">Welcome {}:</p> <span style="margin-left: 50px;display: block">你的邮箱: {},</span> <span style="margin-left: 50px;padding: 0">你的密码:{}</span> </br> </br> </br> <p style="margin-left: 500px">运维团队 {}</p> <p style="color: red">此邮件为系统自动发送,请勿回复!</p> <p>-----------------------------------------------</p> </body> </html> '''.format(username, email, new_password, get_time_now()) SendEmail(email, subject, context) return JsonResponse({"status": "success", "code": 0})
def edit_profile(request, user_id): if str(request.user.id) == user_id: user = User.objects.get(id=user_id) user_profile = models.UserProfile.objects.get(user=user) if request.method == 'GET': if user_profile.profile_picture: pic_file_path = settings.__getattr__('MEDIA_ROOT') + user_profile.profile_picture.url pic_file = open(pic_file_path, 'rb') file_data = {'profile_picture': SimpleUploadedFile(user_profile.profile_picture.name, pic_file.read())} else: file_data = {'profile_picture': None} profile_form = forms.ProfileForm({'location': user_profile.location}, file_data) ctx = {'profile_form': profile_form, 'user_profile':user_profile} return render_to_response('edit_profile.html', RequestContext(request, ctx)) elif request.method == 'POST': profile_form = forms.ProfileForm(request.POST, request.FILES) if profile_form.is_valid(): user_profile.location = request.POST['location'] if 'profile_picture' in request.FILES: user_profile.profile_picture = request.FILES['profile_picture'] user_profile.save() return HttpResponseRedirect(reverse('lernado.accounts.views.view_profile', kwargs={'user_id':user.id})) else: return HttpResponseServerError('profile form is not valid %r ' % profile_form.errors) else: return HttpResponseServerError('This is neither a GET or POST request') else: logger.error('Attempt to edit someone elses profile %r %r' % (request.user.id, user_id)) raise Http404
def settings_to_context(request): """ Context processor for settings """ var_list = list(var for var in dir(settings) if var[:2]!="__") var_dict = {} for var in var_list: var_dict[var] = settings.__getattr__(var) return var_dict
def init(cls) -> _SearchConfig or None: if hasattr(settings, CONFIG_NAME): config_dict = settings.__getattr__(CONFIG_NAME) if 'APP_LIST' not in config_dict: print('未配置 APP_LIST!') return None if 'CONFIG_DIR' not in config_dict: print('未配置 CONFIG_DIR!') return None if 'INDEX_DIR' not in config_dict: print('未配置 INDEX_DIR!') return None search_config = _SearchConfig(config_dict['APP_LIST'], config_dict['CONFIG_DIR'], config_dict['INDEX_DIR']) search_config.logger_name = 'hello' setattr(search_config, 'logger_name', 'hello') for key, value in config_dict.items(): attr_name = key.lower() logger.debug('set {} to {}'.format(attr_name, value)) if hasattr(search_config, attr_name): setattr(search_config, attr_name, value) return search_config else: print('未找到 {} 配置!'.format(MODULE_NAME)) return None
def setting(name): """ Allows you to pull settings to templates {% setting 'FACEBOOK_APP_ID' %} """ return str(settings.__getattr__(name))
def update_defaults(self): """ We make sure to store the most important object defaults here, so we can catch if they change and update them on-objects automatically. This allows for changing default cmdset locations and default typeclasses in the settings file and have them auto-update all already existing objects. """ # setting names settings_names = ("CMDSET_DEFAULT", "CMDSET_OOC", "BASE_PLAYER_TYPECLASS", "BASE_OBJECT_TYPECLASS", "BASE_CHARACTER_TYPECLASS", "BASE_ROOM_TYPECLASS", "BASE_EXIT_TYPECLASS", "BASE_SCRIPT_TYPECLASS") # get previous and current settings so they can be compared settings_compare = zip([ServerConfig.objects.conf(name) for name in settings_names], [settings.__getattr__(name) for name in settings_names]) mismatches = [i for i, tup in enumerate(settings_compare) if tup[0] and tup[1] and tup[0] != tup[1]] if len(mismatches): # can't use any() since mismatches may be [0] which reads as False for any() # we have a changed default. Import relevant objects and run the update from src.objects.models import ObjectDB #from src.players.models import PlayerDB for i, prev, curr in ((i, tup[0], tup[1]) for i, tup in enumerate(settings_compare) if i in mismatches): # update the database print " one or more default cmdset/typeclass settings changed. Updating defaults stored in database ..." if i == 0: [obj.__setattr__("cmdset_storage", curr) for obj in ObjectDB.objects.filter(db_cmdset_storage__exact=prev)] if i == 1: [ply.__setattr__("cmdset_storage", curr) for ply in PlayerDB.objects.filter(db_cmdset_storage__exact=prev)] if i == 2: [ply.__setattr__("typeclass_path", curr) for ply in PlayerDB.objects.filter(db_typeclass_path__exact=prev)] if i in (3,4,5,6): [obj.__setattr__("typeclass_path",curr) for obj in ObjectDB.objects.filter(db_typeclass_path__exact=prev)] if i == 7: [scr.__setattr__("typeclass_path", curr) for scr in ScriptDB.objects.filter(db_typeclass_path__exact=prev)] # store the new default and clean caches ServerConfig.objects.conf(settings_names[i], curr) ObjectDB.flush_instance_cache() PlayerDB.flush_instance_cache() ScriptDB.flush_instance_cache() # if this is the first start we might not have a "previous" setup saved. Store it now. [ServerConfig.objects.conf(settings_names[i], tup[1]) for i, tup in enumerate(settings_compare) if not tup[0]]
def django_settings(request): "A context processor that provides django settings" s_dict = {} for atr in settings.get_all_members(): if ('A'<atr[0]) and (atr[0]<'Z'): s_dict[atr] = settings.__getattr__(atr) return s_dict
def __init__(self): self.settings = { 'LDAP_SERVER_URI': 'ldap://localhost', 'LDAP_SEARCHDN': 'dc=localhost', 'LDAP_SCOPE': ldap.SCOPE_SUBTREE, 'LDAP_SEARCH_FILTER': 'cn=%s', 'LDAP_UPDATE_FIELDS': True, 'LDAP_PREBINDDN': None, 'LDAP_PREBINDPW': None, 'LDAP_BINDDN': None, 'LDAP_BIND_ATTRIBUTE': None, 'LDAP_FIRST_NAME': None, 'LDAP_LAST_NAME': None, 'LDAP_FULL_NAME': None, 'LDAP_GID': None, 'LDAP_SU_GIDS': None, 'LDAP_STAFF_GIDS': None, 'LDAP_ACTIVE_FIELD': None, 'LDAP_ACTIVE': None, 'LDAP_EMAIL': None, 'LDAP_DEFAULT_EMAIL_SUFFIX': None, 'LDAP_OPTIONS': None, 'LDAP_DEBUG': True, } # Load settings from settings.py, put them on self.settings # overriding the defaults. for var in self.settings.iterkeys(): if hasattr(settings, var): self.settings[var] = settings.__getattr__(var)
def get_setting(settings_name): if isinstance(settings_name, str): try: return settings.__getattr__(settings_name) except AttributeError as e: pass return ""
def render(self, context): try: context[self.context_variable] = settings.__getattr__( self.variable_name) except AttributeError: context[self.context_variable] = False return ""
def render( self, context ): for setting_name in self.setting_names: try: val = settings.__getattr__( setting_name ) except AttributeError: val = None context[ setting_name ] = val return ''
def render(self, context): for setting_name in self.setting_names: try: val = settings.__getattr__(setting_name) except AttributeError: val = None context[setting_name] = val return ''
def settings_value(name): """ This Tag allows to access values from the configuration file in the templates. """ try: return settings.__getattr__(name) except AttributeError: return ""
def settings_get(key): """ helper function to ease access to settings module """ if hasattr(settings, key): return settings.__getattr__(key) else: return None
def __getitem__(self, name): if not self._is_loaded: raise Exception("settings have not been loaded") try: return self._local_settings[name] except: pass return django_settings.__getattr__(name)
def test_settings_in_context(self): user = User.objects.create_user('john', '*****@*****.**', 'john') user.save() response = self.client.post('/accounts/login/', {'username': '******', 'password': '******'}) response = self.client.get('/') var_list = list(var for var in dir(settings) if var[:2]!="__") for var in var_list: self.assertEqual(response.context[var], settings.__getattr__(var))
def settings_get(key): """ helper function to ease access to settings module """ #XXX deprecate. shouuld use getattr(settings, 'foo', default) if hasattr(settings, key): return settings.__getattr__(key) else: return None
def get_setting(setting): """ Get a setting from django conf based on setting config in __init__.py . If not set, falls back on defaults. """ try: return settings.__getattr__(es_setting_config[setting]) except AttributeError: return default_es_settings[setting]
def get_setting(attribute, default): """ Returns the value of a Django setting named by the string, attribute, or a default value """ try: return settings.__getattr__(attribute) except AttributeError: return default
def getsetting(name, default=None): """Gets a django setting value by name, or the default if no value is set. """ try: # For some reason there is no sensible way to check if a setting is # defined... return settings.__getattr__(name) except AttributeError: return default
def setting(name): """Tag that provides access to properties from the django.settings dictionary. Usage: {% setting KEY %} where KEY is the key in the dictionary you want Values are returned as strings. """ return str(settings.__getattr__(name))
def handle(self, **options): for (setting_name, default) in settings.REQUIRED_SETTINGS: try: if settings.__getattr__(setting_name) != default: continue except AttributeError: pass print("Error: You must set %s in /etc/zulip/settings.py." % (setting_name,)) sys.exit(1)
def handle(self, *args: Any, **options: Any) -> None: for (setting_name, default) in settings.REQUIRED_SETTINGS: try: if settings.__getattr__(setting_name) != default: continue except AttributeError: pass print("Error: You must set %s in /etc/zulip/settings.py." % (setting_name,)) sys.exit(1)
def index(request, template_name, param=None): if mobileBrowser(request): template_name = 'public/m_index.html' context = { 'opbeatOrgId': settings.OPBEAT_WEBSITE.get('ORGANIZATION_ID'), 'opbeatAppId': settings.OPBEAT_WEBSITE.get('APP_ID'), 'LOCALYTICS_KEY': settings.__getattr__('LOCALYTICS_KEY'), 'GOOGLE_ANALYTICS_UNIVERSAL_KEY': settings.__getattr__('GOOGLE_ANALYTICS_UNIVERSAL_KEY'), 'show_chat_option': getattr(settings, 'SHOW_CHAT_OPTION', False), 'chat_option_to_show': getattr(settings, 'CHAT_OPTION_TO_SHOW', ''), } return render_to_response(template_name, context=context, context_instance=RequestContext(request))
def get_settings(cls, tab=None): sts = cls.objects.all() result = {} for setting in sts: if tab and not setting.tab == tab: continue r = None if hasattr(settings, setting.key): r = settings.__getattr__(setting.key) result[setting.key] = r return result
def check_config() -> None: for (setting_name, default) in settings.REQUIRED_SETTINGS: # if required setting is the same as default OR is not found in settings, # throw error to add/set that setting in config try: if settings.__getattr__(setting_name) != default: continue except AttributeError: pass raise CommandError("Error: You must set %s in /etc/zulip/settings.py." % (setting_name,))
def get_cookie(request, user_id=""): if not user_id: userid = request.COOKIES.get("userid") else: userid = user_id cookies_variable_name = 'cookies_{0}'.format(userid) try: presend_cookie = settings.__getattr__(cookies_variable_name) except Exception as e: presend_cookie = "" return userid, presend_cookie
def get_conf(key): """Get configuration from settings or env. :param key: Key of the configuration. :return: Value of the configuration. """ if hasattr(settings, key): return settings.__getattr__(key) if key in os.environ: return os.environ[key] return None
def render(self, context): try: setting = settings.__getattr__(self.setting) except: setting = None if self.varname: context[self.varname] = setting return '' else: return setting
def get_condision(): f = Forecast.objects.get(id=1) is_cached = "false" ws = cache.get('ws') if ws == None: ws = Weather(f.partner_id, f.key, f.location_id) cache.set('ws', ws, 120) else: is_cached = "true" return {'rt': ws.rt, 'cached': is_cached, 'ws': ws, 'media_url': settings.__getattr__('MEDIA_URL')}
def check_config() -> None: for (setting_name, default) in settings.REQUIRED_SETTINGS: try: if settings.__getattr__(setting_name) != default: continue except AttributeError: pass raise CommandError( "Error: You must set %s in /etc/zulip/settings.py." % (setting_name, ))
def values(ts): ts = settings.__getattr__(ts) lts = len(ts) step = 100/lts a = [] added = 0 for t in ts: a.append(added) added = added + step a[-1] = 100 return a
def check_config() -> None: for (setting_name, default) in settings.REQUIRED_SETTINGS: # if required setting is the same as default OR is not found in settings, # throw error to add/set that setting in config try: if settings.__getattr__(setting_name) != default: continue except AttributeError: pass raise CommandError(f"Error: You must set {setting_name} in /etc/zulip/settings.py.")
def decorator(*args, **kwargs): is_set = False try: if settings.__getattr__(self.key): # We can't do the actual execution because we're in a try-block is_set = True except: pass if is_set: return func(*args, **kwargs) raise Http404
def profile_pic(request, user_id): user = User.objects.get(id=user_id) user_profile = models.UserProfile.objects.get(user=user) if user_profile.profile_picture: fpath = settings.__getattr__('MEDIA_ROOT') + user_profile.profile_picture.url else: fpath = settings.DEFAULT_PERSON_IMAGE content = open(fpath, "rb") # content can be a String or an iterable return HttpResponse(content, mimetype=mimetypes.guess_type(fpath))
def update_defaults(self): """ We make sure to store the most important object defaults here, so we can catch if they change and update them on-objects automatically. This allows for changing default cmdset locations and default typeclasses in the settings file and have them auto-update all already existing objects. """ # setting names settings_names = ("CMDSET_CHARACTER", "CMDSET_PLAYER", "BASE_PLAYER_TYPECLASS", "BASE_OBJECT_TYPECLASS", "BASE_CHARACTER_TYPECLASS", "BASE_ROOM_TYPECLASS", "BASE_EXIT_TYPECLASS", "BASE_SCRIPT_TYPECLASS", "BASE_CHANNEL_TYPECLASS") # get previous and current settings so they can be compared settings_compare = zip([ServerConfig.objects.conf(name) for name in settings_names], [settings.__getattr__(name) for name in settings_names]) mismatches = [i for i, tup in enumerate(settings_compare) if tup[0] and tup[1] and tup[0] != tup[1]] if len(mismatches): # can't use any() since mismatches may be [0] which reads as False for any() # we have a changed default. Import relevant objects and # run the update from evennia.objects.models import ObjectDB from evennia.comms.models import ChannelDB #from evennia.players.models import PlayerDB for i, prev, curr in ((i, tup[0], tup[1]) for i, tup in enumerate(settings_compare) if i in mismatches): # update the database print(" %s:\n '%s' changed to '%s'. Updating unchanged entries in database ..." % (settings_names[i], prev, curr)) if i == 0: ObjectDB.objects.filter(db_cmdset_storage__exact=prev).update(db_cmdset_storage=curr) if i == 1: PlayerDB.objects.filter(db_cmdset_storage__exact=prev).update(db_cmdset_storage=curr) if i == 2: PlayerDB.objects.filter(db_typeclass_path__exact=prev).update(db_typeclass_path=curr) if i in (3, 4, 5, 6): ObjectDB.objects.filter(db_typeclass_path__exact=prev).update(db_typeclass_path=curr) if i == 7: ScriptDB.objects.filter(db_typeclass_path__exact=prev).update(db_typeclass_path=curr) if i == 8: ChannelDB.objects.filter(db_typeclass_path__exact=prev).update(db_typeclass_path=curr) # store the new default and clean caches ServerConfig.objects.conf(settings_names[i], curr) ObjectDB.flush_instance_cache() PlayerDB.flush_instance_cache() ScriptDB.flush_instance_cache() ChannelDB.flush_instance_cache() # if this is the first start we might not have a "previous" # setup saved. Store it now. [ServerConfig.objects.conf(settings_names[i], tup[1]) for i, tup in enumerate(settings_compare) if not tup[0]]
def get(self, name, default=None): """ Returns the value of the named setting. If there is no such setting, then the default value is returned. """ if not self._is_loaded: raise Exception("settings have not been loaded") try: return self._local_settings[name] except: pass try: return django_settings.__getattr__(name) except: pass return default
def get_condision(): f = Forecast.objects.get(id=1) is_cached = "false" ws = cache.get('ws') if ws == None: ws = Weather(f.partner_id, f.key, f.location_id) cache.set('ws', ws, 120) else: is_cached = "true" return { 'rt': ws.rt, 'cached': is_cached, 'ws': ws, 'media_url': settings.__getattr__('MEDIA_URL') }
def display_date(event_date): loc = settings.__getattr__('LANGUAGE_CODE') if not event_date: return ''; elif (__is_today(event_date)): return "Heute, " + event_date.strftime("%H:%M") elif (__is_tomorrow(event_date)): return "Morgen, " + event_date.strftime("%H:%M") elif (__is_the_day_after_tomorrow(event_date)): return "Übermorgen, " + event_date.strftime("%H:%M") else: weekday = ugettext (event_date.strftime("%A"))[:2] day = event_date.day month = ugettext (event_date.strftime("%B"))[:3] time = event_date.strftime("%H:%M") return weekday + ", " + str(day) + ". " + month + " " + time
def render(self, context): return settings.__getattr__(str(self.arg))
def FotoKontrol(dosyayolu): import os from django.conf import settings return os.path.isfile( str(settings.__getattr__("BASE_DIR")) + "/media/" + str(dosyayolu))
def setting(name): return str(settings.__getattr__(name))