开发者

Using KWallet in PyQt4

开发者 https://www.devze.com 2022-12-18 01:54 出处:网络
It would 开发者_如何学Cbe great if anyone could show me how to use KWallet with pyqt4Tutorial in the Python command line

It would 开发者_如何学Cbe great if anyone could show me how to use KWallet with pyqt4


Tutorial in the Python command line

First I will show how kwallet can be used from the Python command line to read and write a password:

$ python

# We import the necessary modules.
>>> from PyKDE4.kdeui import KWallet
>>> from PyQt4 import QtGui

# We create a QApplication. We will not use it, but otherwise
# we would get a "QEventLoop: Cannot be used without
# QApplication" error message.
>>> app = QtGui.QApplication([])

# We open the wallet.
>>> wallet = KWallet.Wallet.openWallet(
                 KWallet.Wallet.LocalWallet(), 0)

# We create a folder in which we will store our password,
# and set it as current.
>>> wallet.createFolder('myfolder')
True
>>> wallet.hasFolder('myfolder')
True
>>> wallet.setFolder('myfolder')
True

# We read the password (which does not exist yet), write it,
# and read it again.
>>> wallet.readPassword('mykey')
(0, PyQt4.QtCore.QString(u''))
>>> wallet.writePassword('mykey', 'mypassword')
0
>>> wallet.readPassword('mykey')
(0, PyQt4.QtCore.QString(u'mypassword'))

Tutorial as a Python module

Usually you want to create some simple functions to wrap around the kwallet methods. The following Python module can open the wallet, get and set a password:

#!/usr/bin/python

from PyKDE4.kdeui import KWallet
from PyQt4 import QtGui

def open_wallet():
    app = QtGui.QApplication([])
    wallet = KWallet.Wallet.openWallet(
                 KWallet.Wallet.LocalWallet(), 0)
    if not wallet.hasFolder('kwallet_example'):
        wallet.createFolder('kwallet_example')
    wallet.setFolder('kwallet_example')
    return wallet

def get_password(wallet):
    key, qstr_password = wallet.readPassword('mykey')

    # converting the password from PyQt4.QtCore.QString to str
    return str(qstr_password)

def set_password(wallet, password):
    wallet.writePassword('mykey', password)

It can be used in the following way:

$ python
>>> import kwallet_example
>>> wallet = kwallet_example.open_wallet()
>>> kwallet_example.set_password(wallet, 'mypass')
>>> kwallet_example.get_password(wallet)


Well i found a good example about it in here, you will also need to use PyKDE4 not only PyQt.

0

精彩评论

暂无评论...
验证码 换一张
取 消