Best way to create user accounts from a file in Python? - python

I am trying to have the ability to mass create user accounts from a file that I upload in Python. So instead of creating users one at a time I can be giving a list of X amount of users and quickly create them. So for instance if I have a file(newusers.csv) that contains the usernames below how would I go about easily doing this?
First name, Last name, Username.
tom cat tcat11
Jerry Mouse Jmouse21
Mini Mouse Mmouse
Below is the code I have which is supposed to create the users:
def user_account():
userInformation = readFile("newusers.csv")
try:
subprocess.run(['useradd','-p', userInformation[1:]])
except:
print(f"failed to add user.")
sys.exit(1)

I don't know what specific options etc. you want in your useradd command so that i'm leaving out of this. However regarding the approach: This is one way you could approach it by creating a User class.
import csv
class User:
def __init__(self, firstname, lastname, username):
self.firstname = firstname
self.lastname = lastname
self.username = username
def save(self):
try:
# WHATEVER COMMAND AND OPTIONS YOU ARE LOOKING TO RUN
# USING self.username, ETC. AS ARGS
except:
print("failed to add user")
sys.exit(1) # if you don't want to attempt any of the other users
#staticmethod
def mass_save(users):
for user in users:
user.save()
#staticmethod
def read_users_from_file(file_path):
with open(file_path, "rt") as f:
users = csv.reader(f)
next(users) # Skip header row
return [User(*row) for row in users] # Unpack each userinfo row from csv upon instantiation
if __name__ == "__main__":
users = User.read_users_from_file("users.csv")
User.mass_save(users)

Related

Accessing and checking the attributes of an object's instance, like a "username" attribute in a "User" object for a login page

I created a class whose parameters are user inputs and the attributes are saved as a dictionary into a file with json, to be re-read by python. Now, I want to be able to access the information in that file(the "username" attribute) from a separate file. If the username matches, then you successfully log in.
File Name: create_user_dataset
"""THIS PROGRAM CREATES A USER AND SIMPLY STORES ITS INFO IN A TXT FILE TO BE RE-READ BY PYTHON"""
from pip._vendor.distlib.compat import raw_input
import json
class User():
'''simulates a user for a social network or pc'''
def __init__(self, first_name, last_name, username, location, *interests):
'''initialize attributes of user class'''
self.first_name = first_name.title()
self.last_name = last_name.title()
self.username = username
self.location = location.title()
self.interests = interests
#classmethod
def get_userinfo(cls):
'''creates a variable to store user inputs that correspond to User attributes'''
first = raw_input("Welcome. PLease Enter Your First Name: ")
last = raw_input("Please Enter Your Last Name: ")
user = raw_input("Username: ")
location = raw_input("What is your location? : ")
interests = []
print("List some of your interests (Press 'Q' Key to End Program.)")
active = True
while active:
'''infinite loop that creates elements in a list until user quits'''
interest = input().strip()
if interest == 'q':
active = False
else:
interests.append(interest)
print("Press 'Q' Key to End Program.")
return cls(first, last, user, location, interests)
"""cls fills in the attributes that would go inside of a given User instance"""
def to_json(self):
return json.dumps({"first": self.first_name, "last": self.last_name, "username": self.username,
"location": self.location, "interests": self.interests})
#classmethod
def from_json(cls, j):
dct = json.loads(j)
return cls(dct["first"], dct["last"], dct["username"], dct["location"], dct["interests"])
The second file simply creates instances of User:
File Name: create_user_frontend
"""THIS PROGRAM CREATES INSTANCES OF USER AND STORES THEIR INFO IN A FILE"""
from create_user_dataset import User
def create(user):
'''creates an instance of User object'''
filename = r'''C:\Users\User\Documents\dataset1.txt'''
with open(filename, 'r+') as f:
'''writes each attribute of User into a file'''
f.write(user.get_userinfo().to_json())
user1 = User
create(user1)
All of the previous works perfectly, I just wanted to provide background. The third file is the problem. The problem is that when I create a new file, while importing the file where my instance of User is stored, console just runs the imported file rather than the file itself.
File Name: user_login
import create_user_frontend as cu
prompt_username = input("Please enter username: ")
print(cu.user1)
This code in create_user_frontend.py will be executed at the time it is imported:
user1 = User
create(user1)
If you don't want it to be executed when it is imported, but only if the file itself is run (e.g. by calling python create_user_frontend.py) you should change it to this:
if __name__ == "__main__:
user1 = User
create(user1)
BTW, this won't fix all of your problems, only the one you asked about.
You still have many problem to handle:
after this change, cu.user1 is no longer available
on the other hand cu.user1 is actually nothing else but create_user_dataset.User, because of the dubious line user1 = User
function create(user) just receives he User class, so it is pointless for it to receive anything
you probably want to call User.get_userinfo() to actually create a user instance
you should definitely either change the names of these functions, or their functionality, because the names don't match what they do:
User.get_userinfo does not get user info - it creates a User instance
create(user) neither takes a user instance as argument, nor does it return a new user - it creates a user instance, dumps its contents into json and then throws away the instance in the same line

Class instance has no attribute, error when calling a function in Flask

I am trying to call a function on button click using flask. Here is a snippet of my code to make my question clearer.
class User:
def __init__(self, username):
self.username = username
def find(self):
user = graph.find_one("User", "username", self.username)
return user
def add_restaurant(self, name, cuisine, location):
user=self.find()
restaurant = Node("Restaurant", id=str(uuid.uuid4()),name=name)
graph.create(restaurant)
graph.create(rel(user,"LIKES", restaurant))
rest_type = Node("Cuisine", cuisine=cuisine)
graph.create(rest_type)
graph.create(rel(restaurant,"SERVES", rest_type))
loc = Node("Location", location=location)
graph.create(loc)
graph.create(rel(restaurant, "IN", loc))
The add_restaurant function is supposed to create 3 nodes and their corresponding relationships in Neo4j graph database, and it works fine.
But, when I call this function from my Flask file, I get an
AttributeError: User instance has no attribute 'add_restaurant'
This is the function in the Flask file
#app.route('/add_restaurant', methods=['POST'])
def add_restaurant():
name = request.form['name1']
cuisine = request.form['cuisine1']
location = request.form['location1']
username = session.get('username')
if not name or not cuisine or not location:
if not name:
flash('You must enter a restaurant name')
if not cuisine:
flash('What cuisine does the restaurant belong to')
if not location:
flash('You must enter a location')
else:
User(username).add_restaurant(name, cuisine, location) #Error comes from here.
return redirect(url_for('index'))
name, cuisine, and location are generated from text fields. What am I doing wrong to get this error?
I looked into this thanks to some similar questions here on stack overflow. I think when you create the user instance with
User(username).add_restaurant(name, cuisine, location)
The user is not properly instantiated. Try with:
else:
user = user(username)
user.add_restaurant(name, cuisine, location)
Let us know if this is of any help.

Python - When to create a Class and when to create a Function

Right, so I'm trying to create a Contacts application using Python OOP. I'm fairly new to OOP and still trying to get my head around the concepts.
I understand that a Class is a blueprint for all objects. I like to think of a Class as an entity and each Object is a record of that entity. I am from a Database background so that's why I interpret it like this, feel free to correct me.
Anyways, in the Contacts app I'm making I've created the Class Contacts as outlined below:
class Contacts():
def __init__(self, firstName, lastName, address, groupType,
telephone, mobile, email, photoField):
self.firstName = firstName
self.lastName = lastName
self.address = address
self.groupType = groupType
self.telephone = telephone
self.mobile = mobile
self.email = email
self.photoField = photoField
def showDetails(self):
print("First Name:\t", self.firstName)
print("Last Name:\t", self.lastName)
print("Address:\t", self.address)
print("Telephone:\t", self.telephone)
print("Mobile:\t", self.mobile)
print("Email:\t", self.email)
Now, if I want to add contacts through the Contacts class into the list I'm using to store each contact object, do I have to create an AddContacts class, or do I create a function instead? I don't know if I'm putting my question across well enough for you to understand what I mean?
What I guess I'm trying to say is that adding contacts is a process and if you look at it from a database point of view you wouldn't create a table called "tbl_AddContacts" since you would do that via a query or a stored procedure, so in my view I would define adding contacts being a function. But asking my colleague who does C# programming he says that adding contacts should be defined by a Class.
This is a confusing concept for me, especially since I don't understand how I would link the AddContacts class with the Contacts class, or even how to define an AddContacts class in the first place!.
Here is the function I defined for adding contacts:
def addContacts():
firstName = input("First Name: ")
lastName = input("Last Name: ")
address = input("Address: ")
telephone = input("Telephone: ")
mobile = input("Mobile: ")
email = input("Email: ")
print("\n")
contact = Contacts(firstName, lastName, address, None, telephone, mobile, email, None)
contactsList.append(contact)
pickle.dump(contactsList, open("save.p", "wb"))
Please help me out, since I will turning this into a GUI application (uni assignment).
Adding a contact is doing something, rather than being something, so it would make sense as a method/function rather than a class. I would suggest that your functionality should actually be in two separate places.
Creating a new contact from user input should be a class method of Contact:
class Contact(object):
...
#classmethod
def from_input(cls):
firstName = input("First Name: ")
lastName = input("Last Name: ")
address = input("Address: ")
telephone = input("Telephone: ")
mobile = input("Mobile: ")
email = input("Email: ")
return cls(firstName, lastName, address, None,
telephone, mobile, email, None)
Adding a new contact to the list of contacts should either be:
An instance method of the e.g. AddressBook or ContactList class (or whatever you have holding the contact list); or
A separate function if you don't have a class to hold the Contact instances.
For example:
class AddressBook(object):
...
def add_contact(self, contact=None):
if contact is None:
contact = Contact.from_input()
self.contacts.append(contact)
Now your UI can create a Contact and pass it straight to address_book.add_contact().
First, your Contacts class is more appropriately called Contact, since it only represents a single contact. Your addContacts options can either be a standalone function, or you could make it part of a ContactList class, which manages your list of Contact objects.
class ContactList():
def __int__(self):
self.contact_list = []
def addContact(firstName, lastName, address, telephone, mobile, email):
contact = Contact(firstName, lastName, address, None, telephone, mobile, email, None)
self.contact_list.append(contact)
pickle.dump(contact_list, open("save.p", "wb"))
I would recommend separating the UI interaction piece (all the input() calls) from your function/method, because as you said, eventually this is going to become a GUI app. You should keep the code that's actually getting input from the user separated so you can change it later without having to change any part of Contact or ContactList.

mongoDB: python code issue

could it be the wrong bottle version?
I lookeed in the sessionDAO file provided by the admins, and they do it the same as i do it;
the code:
def __init__(self, db):
self.db = db
self.users = self.db.users
self.SECRET = 'verysecret'
says:
[1] connect to the blog db
[2] select the users collection
and in the login code i have:
def validate_login(self, username, password):
user = None
try:
# XXX HW 2.3 Students Work Here
# you will need to retrieve right document from the users collection.
password = self.make_pw_hash(password)
user = self.users.find({"_id":username,"password":password})
I know self, username and password; it should be a simple find by document, as i wrote it; I now see that there might be a indentation problem, wich i can see it only on stackoverflow, in notepad++ it's not there;
and:
def add_user(self, username, password, email):
password_hash = self.make_pw_hash(password)
user = {'_id': username, 'password': password_hash}
if email != "":
user['email'] = email
try:
# XXX HW 2.3 Students work here
# You need to insert the user into the users collection.
# Don't over think this one, it's a straight forward insert.
self.users.insert(user)
I know self, username, password and email;
The document is prepared by default: user = {'_id': username, 'password': password_hash}
It should be a simple insert: self.users.insert(user)
Whenever you make any change to the source code, you need to restart the server for those changes to take effect.
Change the line
user = self.users.find({"_id":username,"password":password})
to
user = self.users.find_one({"_id":username})

Access a variable in a method under a class in python

class user_management(wx.Panel):
def login(self):
# Login Function can be later integrated to allow users access to your program
username = self.txt_Username.GetValue()
self.frame.SetStatusText("Welcome "+username+" to the system!!")
test = MyApp(0)
test.MainLoop()
How can i access the variable username within another class:
class wizard(wx.wizard.Wizard):
def on_finished(self, evt):
totalscore = self.totalscore
print "Final score: %s" % (totalscore)
user = "c1021358"
db_file="data/data.db"
database_already_exists = os.path.exists(db_file)
con = sqlite3.connect(db_file)
cur = con.cursor()
sql = "INSERT INTO scores (username,totalscore,topic) VALUES ('%s','%s','%s')" % (user,totalscore,tag)
At the moment the user is static, however I want to make this user variable equal to the username taken from the text field box.
Can anyone tell me how I can do this please?
Thank you
Currently username is a local variable and can't be accessed outside of the method. You could make it a member variable by doing something like self.username instead. It would probably be a good idea to initialize it in an __init__ method.
EDIT: katrielalex has the right idea. You probably want to store the username in something that is not part of your user_management panel. This could either be a global variable, or you could make a user class.
class User:
def __init__(self, username):
self.username = username
# Create a global "current_user", with an initial username of None
current_user = User(None)
Then if you can access the username from the global User object:
def login(self):
global current_user
current_user.username = self.txt_Username.GetValue()
Please note this is all very general (for instance, this assumes you can only support one user at a time), but it should be able to get you started.
Well, you need to store the value of username somewhere that both methods can see. The easiest way to do this, but almost certainly not the right one, is to make it a global variable. You can do that using the global keyword:
global username
username = ...
However, you are almost certainly more likely to want to store it as an attribute of some object. I don't know your architecture so I can't tell you where is best to put it, but something like a User or a Settings object would be good.

Categories

Resources