0

同じ日に別の問題が発生するのは嫌いですが、2つは言うまでもなく、アカウントを登録および削除する方法が必要です。スクリプト全体は次のとおりです。

accounts={'Robrajow':'password', 'Hacker':'hack', 'Noob':'lololol1'}
option1=0
option2=0
loop=1
while loop==1:
    print "Welcome to Telemology! You can login, register, delete an account, or exit."
    loginchoice = raw_input("What would you like to do? ")
    if loginchoice=='login':
        choice = raw_input("What is your username? ")
        choice2 = raw_input("What is your password? ")
        if (choice in accounts):
            option1=1
        else:
            option1=0
        if (choice2 == accounts[choice]):
            option2=1
        else
            option2=0
        if option1==1 and option2==1:
            print "Welcome to Telemology,", choice
        else:
            print "The username or password you entered is incorrect. Please try again or register."
    elif loginchoice=='register':
        newuser=raw_input("What is your new username? ")
        if (newuser in accounts):
            newuser=raw_input("That account name is already taken. Please enter another: ")
        newpass=raw_input("What is your new password? ")
        print newuser,", welcome to Telemology!" 
        print newpass, "is your new password!"
        print "Write it down and hide it!"
    elif loginchoice=='delete':
        unsure=raw_input("Do you really want to delete your account? It will never return! ")
        if unsure=='yes':
            choice = raw_input("What is your username? ")
            choice2 = raw_input("What is your password? ")
            if choice in accounts:
                option1=1
            else:
                option1=0
            if choice2 in password:
                option2=1
            else:
                option2=0
            if option1==1 and option2==1:
                print "Goodbye forever,", choice
            else:
                print "The username or password you entered is incorrect."
        elif unsure=='no':
            print "I hoped so."
        else:
            print "Invalid input."
    elif loginchoice==exit:
        print "Goodbye!"
        loop=0
    else:
        print "What? You can only input login, delete, register, or exit."

1つに置き換えることができる多数のエラーと複雑なコード行は無視してください。アカウント(別名辞書エントリ)を登録および削除する方法だけが必要です。

あなたが私のためにスクリプト全体を書き直すことにしたという偶然の機会に、多くの義務がありました。

4

3 に答える 3

4

これはかなり完全な書き直しです:

import hashlib
import getpass

class Auth(object):
    class UserNameTakenError(Exception):
        pass

    def __init__(self, userDict):
        self._users = {name:self.hash(pwd) for name,pwd in userDict.iteritems()}

    def hash(self, pw):
        return hashlib.sha256(pw+"&@#salt)(string)846!^").digest()

    def validate(self, name, pwd):
        return (name in self._users) and (self._users[name]==self.hash(pwd))

    def create(self, name, pwd):
        if name in self._users:
            raise Auth.UserNameTakenError()
        else:
            self._users[name] = self.hash(pwd)

    def delete(self, name, pwd):
        if self.validate(name, pwd):
            del self._users[name]

def getYes(msg):
    return raw_input(msg).lower() in ('y','yes')

class App(object):
    def __init__(self):
        self.auth = Auth({'Robrajow':'password', 'Hacker':'hack', 'Noob':'lololol1'})
        self.actions = {
            'login':    self.doLogin,
            'l':        self.doLogin,
            'register': self.doRegister,
            'r':        self.doRegister,
            'delete':   self.doDelete,
            'd':        self.doDelete,
            'exit':     self.doExit,
            'e':        self.doExit,
            'x':        self.doExit,
            'q':        self.doExit
        }

    def welcome(self):
        return raw_input("\nWelcome to Telemology! You can Login, Register, Delete an account, or Exit.\nWhat would you like to do? ")

    def doLogin(self):
        name = raw_input("What is your username? ")
        pwd = getpass.getpass("What is your password? ")
        if self.auth.validate(name, pwd):
            print "Welcome to Telemology, {0}".format(name)
        else:
            print "The username or password you entered is incorrect. Please try again or register."
        return False

    def doRegister(self):
        name = raw_input("What is your new username? ")
        pwd = getpass.getpass("What is your new password? ")
        try:
            self.auth.create(name, pwd)
            print "{0}, welcome to Telemology!".format(name)
        except Auth.UserNameTakenError:
            print "That account name is already taken. Please try again."
        return False

    def doDelete(self):
        name = raw_input("What is your username? ")
        pwd = getpass.getpass("What is your password? ")
        if self.auth.validate(name, pwd):
            if getYes("Do you really want to delete your account? It will never return! "):
                self.auth.delete(name, pwd)
                print "Goodbye forever, {0}".format(name)
            else:
                print "I hoped so."
        else:
            print "The username or password you entered is incorrect."
        return False

    def doExit(self):
        print "Goodbye!"
        return True

    def run(self):
        while True:
            act = self.welcome().lower()
            if act in self.actions:
                if self.actions[act]():
                    break
            else:
                print "What? You can only input login, delete, register, or exit."

def main():
    myapp = App()
    myapp.run()

if __name__=="__main__":
    main()
于 2010-12-20T01:50:55.983 に答える
3

さて、辞書を使用してアカウントを保存しています。項目を辞書に追加するには、次のようにします。

accounts["newusername"] = "newpassword"

アイテムを削除するには、次のようにします。

del accounts["usernametodelete"]

(ただし、「1行で置き換えることができる複雑なコード行」に取り組むことをお勧めします。これにより、プログラムがはるかに読みやすくなります。たとえば、if/elseステートメントの複雑なセットがある場合オプション1とオプション2を設定して、次のようなものを使用してみませんか:

if choice in accounts and choice2 == accounts[choice]:
于 2010-12-19T21:09:29.927 に答える
0

コードを修正してください。多くのエラーがあります。

これがあなたのやりたいことだと思います。

>>> if username in accounts:   # if the username is in accounts
    if accounts[username] == password:  # check whether the password is same
        del accounts[username]  # if it is, delete the user
    else:
        print 'Password invalid' # else tell the user the password is invalid

そうでない場合は、コメントして更新します。

于 2010-12-19T21:11:28.833 に答える