Passed
Pull Request — master (#69)
by
unknown
01:40
created

nextcloud.compat   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 10
eloc 26
dl 0
loc 56
rs 10
c 0
b 0
f 0

3 Functions

Rating   Name   Duplication   Size   Complexity  
A encode_requests_password() 0 21 5
A encode_string() 0 11 3
A datetime_to_timestamp() 0 11 2
1
# -*- coding: utf-8 -*-
2
"""
3
Tools for python2/3 unicode compatibility
4
"""
5
import six
6
import time
7
8
9
def encode_requests_password(word):
10
    """
11
    Convert the string to bytes (readable by the server)
12
13
    :param word: input string
14
    :returns:    bytes with appropriate encoding
15
    """
16
    if isinstance(word, bytes):
17
        return word
18
19
    ret = word
20
    if six.PY2:
21
        if isinstance(word, six.text_type):
22
            # trick to work with tricks in requests lib
23
            ret = word.encode('utf-8').decode('latin-1')
24
    else:
25
        try:
26
            ret = bytes(word, 'ascii')
27
        except UnicodeEncodeError:
28
            ret = bytes(word, 'utf-8')
29
    return ret
30
31
32
def encode_string(string):
33
    """Encodes a unicode instance to utf-8. If a str is passed it will
34
    simply be returned
35
36
    :param string: str or unicode to encode
37
    :returns     : encoded output as str
38
    """
39
    if six.PY2:
40
        if isinstance(string, six.text_type):
41
            return string.encode('utf-8')
42
    return string
43
44
45
def datetime_to_timestamp(_time):
46
    """
47
    Returns int(<datetime>.timestamp())
48
    """
49
    if six.PY2:
50
        return int(
51
            time.mktime(_time.timetuple()) + _time.microsecond/1000000.0
52
        )
53
    else:
54
        return int(
55
            _time.timestamp()
56
        )
57