Exemplo n.º 1
0
    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>"
Exemplo n.º 2
0
 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)
Exemplo n.º 3
0
    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))
Exemplo n.º 4
0
    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>"
Exemplo n.º 5
0
def get_settings(name, key=None):
    """"""
    if not key:
        return settings.__getattr__(name)
    else:
        dictionary = settings.__getattr__(name)
        return dictionary[key]
Exemplo n.º 6
0
 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
Exemplo n.º 7
0
    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)
Exemplo n.º 8
0
    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)
Exemplo n.º 9
0
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)
Exemplo n.º 10
0
def settings(name):
    """Display settings on template
    
    Usage:
        {% settings 'DEBUG' %}
    """
    return str(_settings.__getattr__(name))
Exemplo n.º 11
0
    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]]
Exemplo n.º 12
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})
Exemplo n.º 13
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
Exemplo n.º 14
0
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
Exemplo n.º 15
0
    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
Exemplo n.º 16
0
def setting(name):
    """
    Allows you to pull settings to templates

    {% setting 'FACEBOOK_APP_ID' %}
    """
    return str(settings.__getattr__(name))
Exemplo n.º 17
0
 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]]
Exemplo n.º 18
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
Exemplo n.º 19
0
 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)
Exemplo n.º 20
0
 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)
Exemplo n.º 21
0
def get_setting(settings_name):
    if isinstance(settings_name, str):
        try:
            return settings.__getattr__(settings_name)
        except AttributeError as e:
            pass
    return ""
Exemplo n.º 22
0
    def render(self, context):
        try:
            context[self.context_variable] = settings.__getattr__(
                    self.variable_name)
        except AttributeError:
            context[self.context_variable] = False

        return ""
Exemplo n.º 23
0
 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 ''
Exemplo n.º 24
0
 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 ''
Exemplo n.º 25
0
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 ""
Exemplo n.º 26
0
def settings_get(key):
    """
    helper function to ease access to settings module
    """
    if hasattr(settings, key):
        return settings.__getattr__(key)
    else:
        return None
Exemplo n.º 27
0
 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)
Exemplo n.º 28
0
 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))
Exemplo n.º 29
0
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 ""
Exemplo n.º 30
0
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
Exemplo n.º 31
0
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]
Exemplo n.º 32
0
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
Exemplo n.º 33
0
Arquivo: util.py Projeto: mit-dig/spim
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
Exemplo n.º 34
0
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
Exemplo n.º 35
0
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))
Exemplo n.º 36
0
    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)
Exemplo n.º 37
0
    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)
Exemplo n.º 38
0
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))
Exemplo n.º 39
0
 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
Exemplo n.º 40
0
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,))
Exemplo n.º 41
0
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
Exemplo n.º 43
0
 def render(self, context):
    try:
       setting = settings.__getattr__(self.setting)
    except:
       setting = None
       
    if self.varname:
       context[self.varname] = setting
       return ''
    else:
       return setting
Exemplo n.º 44
0
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')}
Exemplo n.º 45
0
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, ))
Exemplo n.º 46
0
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
Exemplo n.º 47
0
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.")
Exemplo n.º 48
0
        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
Exemplo n.º 49
0
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))
Exemplo n.º 50
0
        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
Exemplo n.º 51
0
 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]]
Exemplo n.º 52
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
Exemplo n.º 53
0
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')
    }
Exemplo n.º 54
0
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
Exemplo n.º 55
0
 def render(self, context):
     return settings.__getattr__(str(self.arg))
Exemplo n.º 56
0
def FotoKontrol(dosyayolu):
    import os
    from django.conf import settings

    return os.path.isfile(
        str(settings.__getattr__("BASE_DIR")) + "/media/" + str(dosyayolu))
Exemplo n.º 57
0
def setting(name):
    return str(settings.__getattr__(name))
Exemplo n.º 58
0
 def render(self, context):
     return settings.__getattr__(str(self.arg))