Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

# -*- coding: utf-8 -*- 

""" 

@file 

@brief Encrypting, decrypting. 

""" 

import os 

import keyring 

 

 

def _default_name(): 

""" 

Returns a default username. 

 

:: 

 

os.environ.get('USERNAME', os.environ.get('NAME', 'unknown')) 

""" 

return os.environ.get('USERNAME', os.environ.get('NAME', 'unknown')) 

 

 

def get_password(key, username=None): 

""" 

Retrieves a password assocatied to *key*. 

Relies on module :epkg:`keyring`. 

 

@param key key 

@param username username or ``environ['USERNAME']`` if None 

@return password 

 

.. exref:: 

:title: Store and retrieve a password 

 

Module :epkg:`keyring` can be used to store and retrieve a password. 

It is an easy way to avoid letting clear password in the code. 

To store a password: 

 

.. runpython:: 

:showcode: 

 

import keyring 

keyring.set_password("system", "username", "password") 

 

And to retrieve it: 

 

.. runpython:: 

:showcode: 

 

import keyring 

pwd = keyring.get_password("system", "username") 

print(pwd) 

""" 

if username is None: 

username = _default_name() 

return keyring.get_password(key, username) 

 

 

def set_password(pwd, key, username=None): 

""" 

Stores a password assocatied to *key*. 

Relies on module :epkg:`keyring`. 

 

@param pwd password 

@param key key 

@param username username or ``environ['USERNAME']`` if None 

@return password 

""" 

if username is None: 

username = _default_name() 

keyring.set_password(key, username, pwd)