I am accessing data from different accounts from an online platform over their API. I have created a class called Account that holds all the information necessary to access this API. I want to be able to set the account (and the necessary info to gain access) each time before I make an API request. I tried to make a function that will set a global variable Acct to the proper account class instance but after I call choose_account(), Acct continues to return '', is there a better way to handle this type of procedure?
Acct = ''
def choose_account():
global Acct
get = raw_input(r'Adap1, Adap2, Adap3, or Adap4? ')
if get == 'Adap1':
Acct = Adap1
elif get == 'Adap2':
Acct = Adap2
elif get == 'Adap3':
Acct = Adap3
elif get == 'Adap4':
Acct = Adap4
else:
print ("Please type Adap1, Adap2, Adap3, or Adap4 ")
Edit: show Account and Adap1 etc
class Account():
def __init__(self, name, username, password, org_id):
self.name = name
self.username = username
self.password = password
self.org_id = org_id
def update_pw(self, pw):
self.password = pw
Adap1 = Account('Adap1', 'username', 'password', 'org_id')
Sorry, but use of global variables in that way is not usually a good way to go. You are probably new to programming, so I don't want you to feel you are being "told off", but it would be much more sensible to have the function return a value, and then set the global variable with a statement like
Acct = choose_account()
In which case your function ought to look more like this (untested code):
def choose_acct():
while True:
get = raw_input(r'Adap1, Adap2, Adap3, or Adap4? ')
if get == "Adap1":
return Adap1
elif get == "Adap2":
return Adap2
elif get == "Adap3":
return Adap3
elif get == "Adap4":
return Adap4
Better still, you could consider a data-driven approach to the problem, and define a dictionary like
adict = {"Adap1": Adap1, "Adap2": Adap2, "Adap3": Adap3, "Adap4": Adap4}
Then your function could read (again, untested)
def choose_acct():
while True:
get = raw_input(r'Adap1, Adap2, Adap3, or Adap4? ')
result = adict.get(get, None)
if result:
return result
As your experience level grows you will start to recognise the difference between good and bad code, but you made a pretty good attempt.
Related
I have created a program to read a JSON, convert it into a class, then have them do a specific task. I am currently stuck on a specific issue. I am able to use the following line of code to get it to do what I want; add this transaction.
if (user_selection == 1):
transaction = Transaction(date=datetime.strptime("2022-10-05", '%Y-%m-%d').date(), type="BUY", qty=10, price=1000, cost=10)
statement.add_transaction(transaction)
However, I need to get this information through user input.
My classes are in separate files and they look like this.
#dataclass
class Transaction:
def __init__(self, date: date, type: str, qty: float, price: float, cost: float):
self.date = date
self.type = type
self.qty = qty
self.price = price
self.cost = qty*price
#dataclass
class Statement:
def __init__(self):
self.updated_balance: bool = False
self.transaction_list: List[Transaction] = []
self.balance_list: List[Balance] = []
def add_transaction(self, new: Transaction):
self.updated_balance = False
self.transaction_list.append(new)
I did not include the entire code as I believe it should not affect the clarity of my question, however, in the case a user finds it relevant, I can update the question. I would like to emphasize that the code works as intended this way. What I am asking for help with is, to get "date, type, qty, price, and cost as user input instead of how it is currently being passed.
Below is my main in order to clear up any doubts as to how I am calling the functions.
if __name__ == "__main__":
statament = Statement()
load_transactions(statament)
while True:
show_menu()
user_selection = user_input()
if (user_selection == 3):
break
if (user_selection == 1):
transaction = Transaction(date=datetime.strptime("2022-10-05", '%Y-%m-%d').date(), type="BUY", qty=10, price=1000, cost=10)
statament.add_transaction(transaction)
elif (user_selection == 2):
show_balance(statament.get_balance())
I have tried
transaction = Transaction(date=datetime.strptime(input(), '%Y-%m-%d').date(), type="BUY", qty=10, price=1000, cost=10)
which worked, but only for one parameter, and was not include any string in the input to dictate to the user of "what" and "how" I need the input.
ex. input("Enter date in yyyy-mm-dd format")
I’m trying to learn how to utilize class and objects within my Python code. I'm totally overwhelmed by the fact that is is suppose to be a begginingers class and I got this assignment where if something like this:
Class name is IPAdress and there I want properties IP, hostname, ASN and ISP. Also, it has a method which creates similar print like this:
IP: 85.76.129.254
Hostname: 85-76-129-254-nat.elisa-mobile.fi
ASN: 719
ISP: Elisa Mobile
Method can be named as PrintDetails.
Once the class is ready, I want to use it within my Osio9 function as following
Function asks user to input IP, hostname, ASN and ISP. Object is created according to this information.
Object is added to list (initially empty) and information is printed by using the PrintDetails -method
After this user is asked if he/she wants to create a new IP and if answer is yes -> repeat the above process (ask for input), add the new object to a list and print all information from the list with PrintDetails
After input, the list is looped through and it calls each IPAddress object with PrintDetails -method. (Print can look like the example above)
If user doesn’t want to continue inputting IP-addresses, exit the function
I have no clue how to proceed and answer I receive from my teacher is to look from google so here I am.
class IPAddress: ##define class
def __init__(self, IP, hostname, ASN, ISP):
self.ip = ip
self.hostname = hostname
self.asn = asn
self.isp = isp
def PrintDetails(self): ## construction method
print("IP-address: " + str(self.ip) + " | Hostname: " + str(self.hostname) + " | ASN: " + str(self.asn) + "ISP: " + str(self.isp))
def Osio9():
addresses = []
while(true):
ip = str (input("Enter IP address: ")) #ask for user input
hostname = str (input("Enter Hostname: "))
asn = str (input("Enter ASN: "))
isp = str (input("Enter ISP: "))
address = IPAddress
address.isp = isp
addresses.append(address)
for IPAddress in addresses:
IPAddress.PrintDetails(self)
# continueInput = str (input("Do you want to add more IP-addresses (y/n): "))
# if (continueInput == "y"):
# return addresses
#
# else break
I just saw your last update and there are some good ideas in it. Here is one version of the program, which does not completely correspond to your assignment as the main execution is not within a loop but in a if __name__ == '__main__': statement which will execute only when the program is called directly, and not when it is imported or when function part of this program are imported. I highly encourage you to try a small part of the code, one at a time, and then to adapt it to your specific need.
Let's go piece by piece:
#%% Definition of IPAddress
class IPAddress:
def __init__(self, ip, hostname, asn, isp):
self.ip = ip
self.hostname = hostname
self.asn = asn
self.isp = isp
def prettyprint(self):
str2print = f' | IP: {self.ip}\n' +\
f' | Hostname: {self.hostname}\n' +\
f' | ASN: {self.asn}\n' +\
f' | ISP: {self.isp}\n'
print (str2print)
def __key(self):
"""
key method to uniquely identify an object IPAddress.
I defined it as a tuple of the 4 main attributes, but if one of them is
unique it could be directly used as a key.
"""
return (self.ip, self.hostname, self.asn, self.isp)
def __eq__(self, other):
""" == comparison method."""
return isinstance(self, type(other)) and self.__key() == other.__key()
def __ne__(self, other):
""" != comparison method."""
return not self.__eq__(other)
def __hash__(self):
"""Makes the object hashable. Sets can now be used on IPAddress."""
return hash(self.__key())
I am using spyder as an IDE, and the symbol #%% creates sections of code, very similar to matlab, which can be executed in the current console by doing Right-Click -> Run Cell.
I changed the print function to make it more explicit. Strings object can be denoted by 3 symbols: 'str', "str", """str""". Additionnaly, a flag in front can change the behavior of the string. The most usefull ones are f and r.
Formatting a string with either .format() method or the f flag.
value = 1
str1 = 'string to format with value v = {}'.format(value)
str2 = f'string to format with value v = {value}'
You can print both string to see that they are equivalent. The flag f is similar to a .format() call. It allows the element within the brackets {} to be executed before the print. It is especially usefull when you format a string with multiple values.
v1 = 1
v2 = 2
str1 = 'string to format with value v = {} and {}'.format(v1, v2)
str2 = f'string to format with value v = {v1} and {v2}'
I still chose to split the sring into 4 strings and to add them together for a cleaner look of the code. The backslash \ at the end of each line allows python to consider the current line and the next one as the same line. It's a line-split character.
N.B: If you want to know what the flag r does, look into the escape character ;) r flag is especially usefull when working with paths.
Objects can be compared together. For instace, if you try 5==3, python will return False because the integer object 5 is different from the integer object 3. You can implement the == and != method in any object/class you develop. To do so, I first define a unique key for this object in the function __key(). Then the function __eq__ implements == and returns True if both objects compared are created from the same class and have the same key. The method __ne__ implements != and returns True if __eq__ is not True.
N.B: I also added the hash method to make the object hashable. Once the key is define, creating a hash is trivial, since the idea is to be able to uniquely identify each object, which is also done by the key. This definition allows the use of sets, for instance to check if a list has multiple occurence of the same object.
def add_IPAddress(ListOfIPAddresses, IPAddress):
"""
Function adding IPAddress to ListOfIPAddresses if IPAddress is not already
in ListOfIPAddresses.
"""
if IPAddress not in ListOfIPAddresses:
ListOfIPAddresses.append(IPAddress)
print ('IP Address appended:')
IPAddress.prettyprint()
def input_IPAddress():
"""
Ask a user input to create an IPAddress object.
"""
ip = input("Enter IP address: ")
hostname = input("Enter Hostname: ")
asn = input("Enter ASN: ")
isp = input("Enter ISP: ")
return IPAddress(ip, hostname, asn, isp)
Then I splitted the input from the user and the addition to a list of objects into 2 different functions. The function input() already returns a string, thus I removed the str() call to convert.
N.B: Watchout when asking users to input numbers, usually you forget that the input is a string and then your code raises an error because you forget to convert the string to integer or float.
Improvements: I didn't do it here, but usually when using user input, you have to check if the input given is correct. Some simple syntax checks (e.g. the number of '.' characters in the ipadress) can already improve the robustness of a piece of code. You could also use regular expressions with regex to check if the input is conform.
The query_yes_no() is a clean yes/no util which I copied from somewhere.. I usually place it in a util module: folder within the environment path named util with a __init__.py file. More information if you look into the creation of python module.
#%% Main
if __name__ == '__main__':
ListOfIPAddresses = list()
while True:
if not query_yes_no('Do you want to input IP Address?'):
break
ListOfIPAddresses.append(input_IPAddress())
for ipaddress in ListOfIPAddresses:
ipaddress.prettyprint()
print ('--------------------------') # Just pretting a separator
Finally, in the main part, an infinite while loop is broke only if the user replies no (or any of the other negative keyworkds defined in query_yes_no()). Until it is broken, the user will be asked to add a new IPAddress to the list ListOfIPAddresses which will be added if it is not already present inside.
Full code snippet:
# -*- coding: utf-8 -*-
import sys
#%% Definition of IPAddress
class IPAddress:
def __init__(self, ip, hostname, asn, isp):
self.ip = ip
self.hostname = hostname
self.asn = asn
self.isp = isp
def prettyprint(self):
str2print = f' | IP: {self.ip}\n' +\
f' | Hostname: {self.hostname}\n' +\
f' | ASN: {self.asn}\n' +\
f' | ISP: {self.isp}\n'
print (str2print)
def __key(self):
"""
key method to uniquely identify an object IPAddress.
I defined it as a tuple of the 4 main attributes, but if one of them is
unique it could be directly used as a key.
"""
return (self.ip, self.hostname, self.asn, self.isp)
def __eq__(self, other):
""" == comparison method."""
return isinstance(self, type(other)) and self.__key() == other.__key()
def __ne__(self, other):
""" != comparison method."""
return not self.__eq__(other)
def __hash__(self):
"""Makes the object hashable. Sets can now be used on IPAddress."""
return hash(self.__key())
#%% Functions
def add_IPAddress(ListOfIPAddresses, IPAddress):
"""
Function adding IPAddress to ListOfIPAddresses if IPAddress is not already
in ListOfIPAddresses.
"""
if IPAddress not in ListOfIPAddresses:
ListOfIPAddresses.append(IPAddress)
print ('IP Address appended:')
IPAddress.prettyprint()
def input_IPAddress():
"""
Ask a user input to create an IPAddress object.
"""
ip = input("Enter IP address: ")
hostname = input("Enter Hostname: ")
asn = input("Enter ASN: ")
isp = input("Enter ISP: ")
return IPAddress(ip, hostname, asn, isp)
#%% Util
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is True for "yes" or False for "no".
"""
valid = {"yes": True, "y": True, "ye": True,
"no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "
"(or 'y' or 'n').\n")
#%% Main
if __name__ == '__main__':
ListOfIPAddresses = list()
while True:
if not query_yes_no('Do you want to input IP Address?'):
break
ListOfIPAddresses.append(input_IPAddress())
for ipaddress in ListOfIPAddresses:
ipaddress.prettyprint()
print ('--------------------------') # Just pretting a separator
I want to be able to establish a variable with no value in order to fill it in at a later point in my code, based upon the output of another function.
Ex:
variable = ""
...20 lines later...
if function() is 10:
variable = "10"
else:
variable = "5"
print(variable + 20)
Here's my code so far:
yahoo = "smtp.mail.yahoo.com"
hotmail = "smtp.live.com"
def smtpServer():
if "#yahoo.com" in username:
server = smtplib.SMTP(yahoo,587)
if "#hotmail.com" in username:
server = smtplib.SMTP(hotmail,587)
else:
pass
def check():
try:
server.connect(server)
server.login(username,password)
server.quit()
line = f.readline()
cnt = 1
while line:
#UserAndPass = str.split(':') #check login
UserAndPass = line.split(':')
username = str(UserAndPass[0])
password = str(UserAndPass[1])
cnt += 1
server = ""
smtpServer()
check()
With what I have now, I keep getting errors saying that it's undefined, so I'm just not sure how to define it for this purpose. Thank you!
If you want to refer a global variable from within a function, you need to declare it using global yahoo or global hotmail in your function. You also need to declare global server in the functions setting and using the server.
You don't need to initialize the variable to an empty value for this to work.
However, your approach of hardcoding the mail servers for mail addresses is completely broken. Use the MX records provided by the domain name system, they're there for a reason.
Use this for making an empty variable:
variable = None
For your code, you can use server = None.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I am trying to incorporate a regex check for user input in my class. I want a scenario where users can't proceed to enter their name until they enter a valid email address. The current code i have isn't working as expected.
I suppose a while-loop is in order here but i am struggling to implement that in this class. Any assistance is much appreciated.
class test:
def __init__(self):
self.email = input("Enter your email: ")
email_check = re.search(r'[\w.-]+#[\w.-]+.\w+', self.email)
if email_check:
print ('email valid')
else:
print ('email not valid')
self.email = input("Enter your email: ")
sys.exit(0)
self.name = input("Enter your name: ")
You can do it like this.
while True:
self.email = input ("Enter email:")
if valid_email:
break
Substitute valid_email with your way of validating the email address.
You may also be interested in Python check for valid email address? for ways to validate an email address.
First of all - you should not implement any activity of this kind into __init__ method, as one is intended for object fields initialization first place. Consider dedicated 'check_email' method, or whatever name applies best.
Now, regarding your case:
class test:
def __init(self):
# whatever initialization applies
pass
def init_emails():
emails = []
proceed = True
# if you really in need of do/while loop
while proceed:
email = self.input_email()
# your logic for input
if email is not None:
emails.append(email)
# invalid input or cancel
else:
proceed = False
return input
def input_email(self):
value = input('Enter your email:')
# TODO: validate/check input
return proper_value
class test:
def __init__(self):
self.email = self.get_name()
def get_name(self) :
while True:
x = input("Enter your email: ")
if (re.search(r'[\w.-]+#[\w.-]+.\w+', x)) :
return x
This script functions as described, in the end printing the name and email. If you need to use python2.7, use raw_input instead of input. I used for i in range instead of while True to avoid an endless loop.
#!/usr/bin/env python3
import re
import sys
class Test(object):
def __init__(self):
self.email = None
self.name = None
def get_email(self):
for i in range(3):
email = input('Enter your email: ')
if re.search('[\w.-]+#[\w.-]+.\w+', email):
return email
print('Too many failed attempts!')
sys.exit(1)
def get_name(self):
for i in range(3):
name = input('Enter your name: ')
if name:
return name
print('Too many failed attempts!')
sys.exit(1)
def initialize(self):
self.email = self.get_email()
self.name = self.get_name()
print('"{}" <{}>'.format(self.name, self.email))
if __name__ == '__main__':
t = Test()
t.initialize()
Instead of input, try to use raw_input. Like this:
self.email = raw_input("Enter your email:")
There'll be no error anymore.
Hope this helps.
I'm a php programmer who's just getting started with Python. I'm trying to get Python to handle login/logout via database-stored sessions. Things work, but seem inconsistent. For example, sometimes a user isn't logged out. Sometimes users "switch" logins. I'm guessing this has something to do with thread-safety, but I'm just not sure where to begin on how to fix this. Any help would be appreciated. Here's what I have now:
#lib/base.py
def authenticate():
#Confirm login
try:
if user['authenticated'] != True:
redirect_to(controller='login', action='index')
except KeyError:
redirect_to(controller='login', action='index')
#Global variables
user = {}
connection = {}
class BaseController(WSGIController):
#Read if there is a cookie set
try:
session = request.cookies['session']
#Create a session object from the session id
session_logged_in = Session(session)
#If the session is valid, retrieve the user info
if session_logged_in.isValid(remote_addr):
#Set global variables about the logged in user
user_logged_in = User(session_logged_in.user_id)
user['name'] = c.name = user_logged_in.name
user['name_url'] = c.name_url = user_logged_in.name_url
user['first_name'] = c.first_name = user_logged_in.first_name
user['last_name'] = c.last_name = user_logged_in.last_name
user['email'] = c.email = user_logged_in.email
user['about'] = c.about = user_logged_in.about
user['authenticated'] = c.authenticated = True
user['profile_url'] = c.profile_url = user_logged_in.profile_url
user['user_thumb'] = c.user_thumb = user_logged_in.user_thumb
user['image_id'] = c.image_id = user_logged_in.image_id
user['id'] = c.user_id = user_logged_in.id
#Update the session
session_logged_in.current_uri = requested_url
session_logged_in.update()
#If no session has been set, do nothing
except KeyError:
user['authenticated'] = False
I can then access the user{} global from my controllers:
#controllers/profile.py
from project.lib.base import BaseController, user
class ProfileController(BaseController):
def index(self, id=None, name_url=None):
#If this is you
if user['id'] == 1
print 'this is you'
Is there a better way to do this? Thanks for your help.
Pylons has a 'sessions' object that exists to handle this kind of situation. The example on the Pylons website seems to match what you want.
I think you are seeing problems because of the globals 'user' and 'connection'. Pylons has a globals object that is designed to share information between all controllers and is not reset on each request.