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

nextcloud.compat.encode_string()   A

Complexity

Conditions 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 11
rs 10
c 0
b 0
f 0
cc 3
nop 1
1
# -*- coding: utf-8 -*-
2
"""
3
Tools for python2/3 unicode compatibility
4
"""
5
import six
6
7
8
def encode_requests_password(word):
9
    """
10
    Convert the string to bytes (readable by the server)
11
12
    :param word: input string
13
    :returns:    bytes with appropriate encoding
14
    """
15
    if isinstance(word, bytes):
16
        return word
17
18
    ret = word
19
    if six.PY2:
20
        if isinstance(word, six.text_type):
21
            # trick to work with tricks in requests lib
22
            ret = word.encode('utf-8').decode('latin-1')
23
    else:
24
        try:
25
            ret = bytes(word, 'ascii')
26
        except UnicodeEncodeError:
27
            ret = bytes(word, 'utf-8')
28
    return ret
29
30
31
def encode_string(string):
32
    """Encodes a unicode instance to utf-8. If a str is passed it will
33
    simply be returned
34
35
    :param string: str or unicode to encode
36
    :returns     : encoded output as str
37
    """
38
    if six.PY2:
39
        if isinstance(string, six.text_type):
40
            return string.encode('utf-8')
41
    return string
42