示例#1
0
 def test_closeduser(self):
     testdate = datetime.datetime.now()
     user = User(1, 'estigum', 'Erik Stigum', 'Test123',
                 'This is a test Account', UserState.OPEN, 'system',
                 testdate, 'estigum', testdate)
     user.Status = UserState.CLOSED
     self.assertEqual(user.Status, UserState.CLOSED)
示例#2
0
文件: app.py 项目: shernandezp/python
def hello():
    userAccess = UserAccess()
    if request.method == 'POST':
        result = request.form
        newUser = User()

        for key, value in result.items():
            if key == "txtname":
                newUser.username = value
            elif key == "txtpass":
                newUser.password = value
            elif key == "txtemail":
                newUser.email = value
        userAccess.InsertUser(newUser)

    users = userAccess.GetUsers()
    return render_template("index.html", users=users)
示例#3
0
 def test_newuser(self):
     user = User(1, 'estigum', 'Erik Stigum', 'Test123',
                 'This is a test Account', UserState.OPEN, 'system')
     self.assertEqual(user.UserName, 'estigum')
     self.assertEqual(user.Password, 'Test123')
     self.assertEqual(user.UserId, 1)
     self.assertEqual(user.Comment, 'This is a test Account')
     self.assertEqual(user.Status, UserState.OPEN)
     self.assertEqual(user.FullName, 'Erik Stigum')
     self.assertEqual(user.CreatedBy, 'system')
     self.assertEqual(user.LastUpdatedBy, 'system')
示例#4
0
    def GetAllUsers(self):
        FileUsersR = open(path + "Users/Users.csv", newline='')
        reader = csv.DictReader(FileUsersR, delimiter=',')
        user = []
        for line in reader:
            user.append(
                User(line["user_id"], line["phone"], line["first_name"],
                     line["last_name"], line["middle_name"]))

        FileUsersR.close()
        return user
示例#5
0
    def Add(self, username, fullname, password, comment, createdBy):

        if not (self.Get(username) is None):
            raise Exception("User already exists")

        self.__CurrentUserId = self.__CurrentUserId + 1
        user = User(self.__CurrentUserId, username, fullname, password,
                    comment, UserState.OPEN, createdBy)

        self.__Users[user.UserName] = user

        return user
示例#6
0
def verifyRegistration (user):
    """
    Verify registration
    if its True - add user to db

    :param obj(user)
    :return True or error code

    user[0] = firstName
    user[1] = lastName
    user[2] = userName
    user[3] = post Code
    user[4] = street name
    user[5] = house number
    user[6] = email
    user[7] = email confirmation
    user[8] = password
    user[9] = password confirmation
    """

    # Check if entries contain spaces or empty fields
    for i in range(len(user)):
        if not user[i]:
            return "empty fields"
        elif " " in user[i]:
            if i != 4:
                return "Contain spaces"

    # check if user exist
    with open("Data/users.csv", 'r') as f:
        l = list(csv.reader(f))
        my_dict = {i[0]: [x for x in i[1:]] for i in zip(*l)}
        if user[2] in my_dict.get('login'):
            return "User already exist"

    if user[6] != user[7]:
        return "Email does not match"

    if not verifyEmail(user[6]):
        return "Invalid email address"

    if user[8] != user[9]:
        return "Password does not match"
    else:
        if len(user[8]) < 4:
            return "Password is too short"

    address = "{} - {}, {}".format(user[3], user[5], user[4])
    newUser = User(user[2], user[0], user[1], user[8], user[6], address, 999)
    wf.add_user(newUser)
    createUserFolder(user[2])

    return True
    def __init__(self, xml_user_file_path, xml_badges_file_path):
        with codecs.open(xml_user_file_path, "r", "utf-8") as file:
            soup = BeautifulSoup(file, "html.parser")
        all_post = soup.find_all("row")
        self.map_of_user = {}
        map_user_badges = UserParser.read_badges(xml_badges_file_path)

        for post in all_post:
            attr_dic = post.attrs
            user_id = int(attr_dic["id"])
            creation_date = None
            age = None
            location = None
            reputation = None
            views = None
            about_me = None
            up_votes = None
            down_votes = None
            website_url = None
            last_access_date = None
            display_name = None

            if "creationdate" in attr_dic:
                creation_date = (attr_dic["creationdate"])
            if "age" in attr_dic:
                age = int(attr_dic["age"])
            if "location" in attr_dic:
                location = (attr_dic["location"])
            if "reputation" in attr_dic:
                reputation = int(attr_dic["reputation"])
            if "views" in attr_dic:
                last_access_date = int(attr_dic["views"])
            if "websiteurl" in attr_dic:
                website_url = (attr_dic["websiteurl"])
            if "downvotes" in attr_dic:
                down_votes = int(attr_dic["downvotes"])
            if "upvotes" in attr_dic:
                up_votes = int(attr_dic["upvotes"])
            if "aboutme" in attr_dic:
                about_me = (attr_dic["aboutme"])
            if "lastaccessdate" in attr_dic:
                last_access_date = (attr_dic["lastaccessdate"])
            if "displayname" in attr_dic:
                display_name = (attr_dic["displayname"])
            lst_badges = None
            if user_id in map_user_badges:
                lst_badges = map_user_badges[user_id]

            user = User(user_id, reputation, age, location, creation_date,
                        views, lst_badges, about_me, up_votes, down_votes,
                        website_url, last_access_date, display_name)
            self.map_of_user[user_id] = user
示例#8
0
    def GetUser(self, user_id):
        # РАЗОБРАТЬСЯ С ENUMERATE!
        fileUsersR = open(self.fUsers, newline='')
        fileUserRoleR = open(self.fUserRole, newline='')
        fileRolesR = open(self.fRoles, newline='')
        # ищу пользователя по user_id
        reader = csv.DictReader(fileUsersR, delimiter=',')
        user = User(-1, -1, -1, -1, -1)
        for i, line in enumerate(reader, 1):
            if (i == user_id):
                user = User(line[self.dUser['user_id']],
                            line[self.dUser['phone']],
                            line[self.dUser['first_name']],
                            line[self.dUser['last_name']],
                            line[self.dUser['middle_name']])
                break
        reader = csv.DictReader(fileUserRoleR, delimiter=',')
        role_id = 0
        # зная user_id, нахожу соответсвующее значение role_id
        for i, line in enumerate(reader, 1):
            if (i == user_id):
                role_id = int(line[self.dRole['role_id']])
                break

        # зная role_id, нахожу полную информацию об этой роли
        reader = csv.DictReader(fileRolesR, delimiter=',')
        role = Role(-1, -1)
        for i, line in enumerate(reader, 1):
            if (i == role_id):
                role = Role(line[self.dRole['role_id']],
                            line[self.dRole['description']])
                break
        #
        fileUsersR.close()
        fileUserRoleR.close()
        fileRolesR.close()
        return (user, role)  # tuple()
示例#9
0
 def test_existinguser(self):
     testdate = datetime.datetime.now()
     user = User(1, 'estigum', 'Erik Stigum', 'Test123',
                 'This is a test Account', UserState.OPEN, 'system',
                 testdate, 'estigum', testdate)
     self.assertEqual(user.UserName, 'estigum')
     self.assertEqual(user.Password, 'Test123')
     self.assertEqual(user.UserId, 1)
     self.assertEqual(user.Comment, 'This is a test Account')
     self.assertEqual(user.Status, UserState.OPEN)
     self.assertEqual(user.FullName, 'Erik Stigum')
     self.assertEqual(user.CreatedBy, 'system')
     self.assertEqual(user.CreatedAt, testdate)
     self.assertEqual(user.LastUpdatedBy, 'estigum')
     self.assertEqual(user.LastUpdatedAt, testdate)
    def __init__(self, xml_user_file_path, xml_badges_file_path):
        self.map_of_user = {}
        map_user_badges = UserParserRecord.read_badges(xml_badges_file_path)

        for attr_dic in xmliter(xml_user_file_path, 'row'):
            user_id = int(attr_dic["@Id"])
            creation_date = None
            age = None
            location = None
            reputation = None
            views = None
            about_me = None
            up_votes = None
            down_votes = None
            website_url = None
            last_access_date = None
            display_name = None

            if "@CreationDate" in attr_dic:
                creation_date = (attr_dic["@CreationDate"])
            if "@Age" in attr_dic:
                age = int(attr_dic["@Age"])
            if "@Location" in attr_dic:
                location = (attr_dic["@Location"])
            if "@Reputation" in attr_dic:
                reputation = int(attr_dic["@Reputation"])
            if "@Views" in attr_dic:
                last_access_date = int(attr_dic["@Views"])
            if "@WebsiteUrl" in attr_dic:
                website_url = (attr_dic["@WebsiteUrl"])
            if "@DownVotes" in attr_dic:
                down_votes = int(attr_dic["@DownVotes"])
            if "@UpVotes" in attr_dic:
                up_votes = int(attr_dic["@UpVotes"])
            if "@AboutMe" in attr_dic:
                about_me = (attr_dic["@AboutMe"])
            if "@LastAccessDate" in attr_dic:
                last_access_date = (attr_dic["@LastAccessDate"])
            if "@DisplayName" in attr_dic:
                display_name = (attr_dic["@DisplayName"])
            lst_badges = None
            if user_id in map_user_badges:
                lst_badges = map_user_badges[user_id]

            user = User(user_id, reputation, age, location, creation_date,
                        views, lst_badges, about_me, up_votes, down_votes,
                        website_url, last_access_date, display_name)
            self.map_of_user[user_id] = user
示例#11
0
 def test_lastupdatedbychanged(self):
     user = User(1, 'estigum', 'Erik Stigum', 'Test123',
                 'This is a test Account', UserState.OPEN, 'system')
     user.LastUpdatedBy = 'cstigum'
     self.assertEqual(user.LastUpdatedBy, 'cstigum')
示例#12
0
def verifyRegistration(user):
    """
    Verify registration
    if its True - add user to db

    :param user: list(user)
    :return True or error code

    user[0] = firstName
    user[1] = lastName
    user[2] = userName
    user[3] = post Code
    user[4] = street name
    user[5] = house number
    user[6] = email
    user[7] = email confirmation
    user[8] = password
    user[9] = password confirmation
    user[10] = phone number
    """

    for i in range(len(user)):
        print("index: {}; value: {}".format(i, user[i]))

    # Check if entries contain spaces or empty fields
    for i in range(len(user)):
        if not user[i]:
            return strings.errorEmptyFields
        elif " " in user[i]:
            print("i value:", i)
            if i == 3:
                if " " == user[i]:
                    print("all empty")
                    return strings.errorSpaces
            else:
                print("else")
                if i != 4:
                    if i == 5:
                        continue
                    else:
                        return strings.errorSpaces

    exist = os.path.isfile(strings.filePath_user)
    if exist:
        with open(strings.filePath_user, 'r') as f:
            l = list(csv.reader(f))
            my_dict = {i[0]: [x for x in i[1:]] for i in zip(*l)}
            if user[2] in my_dict.get('login'):
                return strings.errorUserAlreadyExist

    if user[6] != user[7]:
        return strings.errorEmailMismatch

    if not verifyEmail(user[6]):
        return strings.errorInvalidEmail

    if user[8] != user[9]:
        return strings.errorPasswordMismatch
    else:
        if len(user[8]) < 4:
            return strings.errorShortPassword

    if not str(user[10]).isdigit():
        return strings.errorInvalidPhoneNumber

    address = "{} - {}, {}".format(user[3], user[5], user[4])
    newUser = User(user[2], user[0], user[1], user[8], user[6], address,
                   user[10])
    wf.write(newUser, strings.filePath_user, strings.fieldNames_user)
    createUserFolder(user[2])

    return True
示例#13
0
    def GetBorrowedBooks(self):
        # HELP!
        # пытался реализовать все циклы по строкам файлов при помощи enumerate в целях экономии времени работы методов, но возникают проблемы с возвратом указателя в начало файла
        FileBooksR = open(path + "Books/Books.csv", newline='')
        FileUsersR = open(path + "Users/Users.csv", newline='')
        FileAuthorsR = open(path + "Books/Authors.csv", newline='')
        FileAuthorshipR = open(path + "Books/Authorship.csv", newline='')
        FileReadersR = open(path + "Readers.csv", newline='')
        user = []
        book = []
        date1 = []
        date2 = []
        authors = []
        readerReaders = csv.DictReader(FileReadersR, delimiter=',')
        readerUsers = csv.DictReader(FileUsersR, delimiter=',')
        readerBooks = csv.DictReader(FileBooksR, delimiter=',')
        readerAuthorship = csv.DictReader(FileAuthorshipR, delimiter=',')
        readerAuthors = csv.DictReader(FileAuthorsR, delimiter=',')
        # захожу в цикл по строкам файла Readers.csv
        for lineReaders in readerReaders:
            # захожу в цикл по строкам файла Books.csv с фиксированным значением user_id
            FileUsersR.seek(0)  # возвращаю указатель в начало файла
            for lineUsers in readerUsers:
                # нахожу нужного пользователя и добавляю его данные в user[]
                if (lineUsers["user_id"] == lineReaders["user_id"]):
                    user.append(
                        User(lineUsers["user_id"], lineUsers["phone"],
                             lineUsers["first_name"], lineUsers["last_name"],
                             lineUsers["middle_name"]))
                    break
            # захожу в цикл по строкам файла Authorship.csv с фиксированным значением book_id
            FileAuthorshipR.seek(0)  # возвращаю указатель в начало файла
            for lineAuthorship in readerAuthorship:
                # нахожу нужные(ый) author_id
                if (lineAuthorship["book_id"] == lineReaders["book_id"]):
                    # захожу в цикл по строкам файла Authors.csv с фиксированным значением author_id
                    FileAuthorsR.seek(0)  # возвращаю указатель в начало файла
                    for lineAuthors in readerAuthors:
                        # имея author_id нахожу нужного автора и добавляю его в authors[]
                        if (lineAuthorship["author_id"] ==
                                lineAuthors["author_id"]):
                            authors.append(
                                Author(lineAuthors["author_id"],
                                       lineAuthors["first_name"],
                                       lineAuthors["last_name"],
                                       lineAuthors["middle_name"]))
                            break
            # добавляю нужную дату взятия книги в date1[]
            date1.append(lineReaders["borrow_date"])
            # добавляю нужную дату сдачи книги в date2[]
            date2.append(lineReaders["return_date"])
            #
            # захожу в цикл по строкам файла Books.csv с фиксированным значением book_id
            FileBooksR.seek(0)  # возвращаю указатель в начало файла
            for lineBooks in readerBooks:
                # нахожу нужную книгу
                if (lineBooks["book_id"] == lineReaders["book_id"]):
                    # добавляю её в book[]
                    new_list = authors.copy(
                    )  # новый список для устранения проблем с памятью
                    book.append(
                        Book(lineBooks["book_id"], lineBooks["file_path"],
                             lineBooks["title"], lineBooks["year"],
                             lineBooks["publisher"], new_list))
                    authors.clear()
                    break

        FileUsersR.close()
        FileBooksR.close()
        FileAuthorsR.close()
        FileAuthorshipR.close()
        FileReadersR.close()
        return (book, date1, date2, user)  # tuple()