jumpserver/apps/common/utils.py

110 lines
2.5 KiB
Python
Raw Normal View History

2016-09-03 11:05:50 +00:00
# -*- coding: utf-8 -*-
#
from __future__ import unicode_literals
from six import string_types
2016-09-13 17:08:26 +00:00
from itertools import chain
import string
2016-09-15 03:19:36 +00:00
import logging
2016-09-03 11:05:50 +00:00
from django.shortcuts import reverse as dj_reverse
from django.conf import settings
2016-09-07 16:40:59 +00:00
from django.core import signing
2016-09-10 13:08:10 +00:00
from django.utils import timezone
2016-09-03 11:05:50 +00:00
def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None, external=False):
url = dj_reverse(viewname, urlconf=urlconf, args=args, kwargs=kwargs, current_app=current_app)
if external:
url = settings.SITE_URL.strip('/') + url
return url
def get_object_or_none(model, **kwargs):
try:
obj = model.objects.get(**kwargs)
except model.DoesNotExist:
obj = None
return obj
2016-09-07 16:40:59 +00:00
def encrypt(*args, **kwargs):
return signing.dumps(*args, **kwargs)
def decrypt(*args, **kwargs):
return signing.loads(*args, **kwargs)
2016-09-10 13:08:10 +00:00
def date_expired_default():
try:
years = int(settings.CONFIG.DEFAULT_EXPIRED_YEARS)
except TypeError:
years = 70
2016-09-13 17:08:26 +00:00
return timezone.now() + timezone.timedelta(days=365 * years)
def combine_seq(s1, s2, callback=None):
for s in (s1, s2):
if not hasattr(s, '__iter__'):
return []
seq = chain(s1, s2)
if callback:
seq = map(callback, seq)
return seq
def search_object_attr(obj, value='', attr_list=None, ignore_case=False):
"""It's provide a method to search a object attribute equal some value
2016-09-13 17:08:26 +00:00
If object some attribute equal :param: value, return True else return False
class A():
name = 'admin'
age = 7
2016-09-13 17:08:26 +00:00
:param obj: A object
:param value: A string match object attribute
:param attr_list: Only match attribute in attr_list
:param ignore_case: Ignore case
:return: Boolean
"""
2016-09-13 17:08:26 +00:00
if value == '':
return True
try:
object_attr = obj.__dict__
except AttributeError:
return False
2016-09-13 17:08:26 +00:00
if attr_list is not None:
new_object_attr = {}
2016-09-13 17:08:26 +00:00
for attr in attr_list:
new_object_attr[attr] = object_attr.pop(attr)
object_attr = new_object_attr
2016-09-13 17:08:26 +00:00
if ignore_case:
if not isinstance(value, string_types):
return False
if value.lower() in map(string.lower, map(str, object_attr.values())):
2016-09-13 17:08:26 +00:00
return True
else:
if value in object_attr.values():
return True
return False
2016-09-15 03:19:36 +00:00
def get_logger(name=None):
return logging.getLogger('jumpserver.%s' % name)
2016-09-18 16:07:52 +00:00
def int_seq(seq):
try:
return map(int, seq)
except ValueError:
return seq