I want to make a login window , and there are two QlineEdits in this window . We must input the correct account and password in it then login successful.
There are two groups account and password in member.db
First : Account:aaa , Password:000
Second : Account:bbb , Password:111
Here is part of my code: Howerver when I select the data of account , it can't catch the value .
def buttonClicked(self):
model = QSqlQueryModel()
a=model.setQuery("SELECT Password FROM member WHERE Account = values(\'{0}')".format(self.AccountEdit))
if a==self.PasswordEdit.text():
QtGui.QMessageBox.information(self, 'message',"Congratulations !!!")
else:
QtGui.QMessageBox.warning(self, 'message',"Error !!!")
I think the error is in a=model.setQuery("SELECT Password FROM member WHERE Account = values(\'{0}')".format(self.AccountEdit)) this code.
Because I tried to print(a) and it return None .
This is not valid SQL; you should use just WHERE Account = 'name'.
Furthermore, to prevent SQL injection attacks, you should use parameters; this is possible only by using a separate QSqlQuery object:
query = QSqlQuery()
query.prepare("SELECT Password FROM member WHERE Account = ?")
query.bindValue(0, self.AccountEdit)
query.exec_()
model = QSqlQueryModel()
model.setQuery(query)
Related
when a new AWS Account gets created or migrated into our environment the details get put into a DynamoDB, below is an example of the details of stored in the DDB:
{'Count': 57,
'Items': [{'AccountId': 'Account Number Here',
'AccountName': 'Account Name Here',
'Arn': 'arn:here',
'Email': 'email#somecompany.com',
'MainAccount': 'The Main Billing Account',
'Type': 'prod'},
}
I'm wondering if there is some way, I can possibly scan the DDB then when a new entry is added create a CloudWatch billing alarm using my code below, I understand this will need modifying and I'll admit this is very manual and not very automated, which is why I'm enquiring here:
import boto3
my_profile = input(
"Please input the profile name you will use stored in ~\.aws\config: \n"
)
sess = boto3.Session(profile_name=my_profile, region_name="us-east-1")
# US-East-1 as that is where Billing Alarms are handled.
sns_name = input("Enter SNS Topic name with no spaces, you can use underscores: \n")
sns_client = sess.client("sns")
# Creates SNS Topic
result = sns_client.create_topic(Name=sns_name)
for value in result.values():
print(value)
topic_arn = input(
"Copy & Paste Topic ARN from printed result above including arn: : \n"
)
print("Topic Created..")
subscribe_endpoint = input("Enter an email address for the subscription: \n")
print("Subscription created, check your emails and confirm the subscription.")
# Creates Subscription & Sets up email protocol for that particular topic, ammend Topic Arn from previous SNS topic and change enpoint to respective email address.
sns_client.subscribe(
TopicArn=topic_arn, # Grab ARN from list_topics API call.
Protocol="email",
Endpoint=subscribe_endpoint, # Input email address here
ReturnSubscriptionArn=True,
)
cw = sess.client("cloudwatch")
alarm_name = input("Enter an alarm name: \n")
alarm_desc = input("Enter an alarm description: \n")
alarm_threshold = int(input("Enter the alarm threshold in integer values: \n"))
if alarm_threshold == "":
print("please enter integer values only")
exit()
metrics_id = input("Please enter a metric ID,: \n")
linked_account_id = input(
"Please type the account ID in reference to your billing alarm, please note it can take 24hrs for this to appear if recently migrated: \n"
)
# Below creates the alarm, change Name, Description, Threshold and LinkedAccount & Label
cw.put_metric_alarm(
AlarmName=alarm_name,
ActionsEnabled=True,
MetricName="EstimatedCharges",
Namespace="AWS/Billing",
Statistic="Maximum",
Dimensions=[
{"Name": "Currency", "Value": "USD"},
{"Name": "LinkedAccount", "Value": linked_account_id},
],
Period=21600,
AlarmDescription=alarm_desc,
AlarmActions=[topic_arn],
EvaluationPeriods=1,
DatapointsToAlarm=1,
Threshold=alarm_threshold,
ComparisonOperator="GreaterThanOrEqualToThreshold",
TreatMissingData="missing",
)
print("\n")
print(
f"Alarm: {alarm_name} has been created, actioning on topic {topic_arn}. The threshold is {alarm_threshold} to linked account {linked_account_id}, an Email will be sent to {subscribe_endpoint} if this threshold is breached/exceeded."
)
I appreciate the code relies on User Input, however if there is some way to generalize or grab some information from the DDB and use it similar to below:
sns_name = #This can relate to the account name Maybe "AccName_SNS_Topic"
topic_arn = "the topic arn" #I'm fairly new to Python
# so I'm not sure how to pull the exact topic arn from it once it's created and stored
# in the variable.
subscribe_endpoint = "The email address linked to the account in DDB"
alarm_name = "AccountName - Dev or Prod (Stored in type on DDB) - Billing Alarm"
alarm_desc = "As above"
alarm_threshold = 700
# We can skip metrics ID, I don't think we actually need it
linked_account_id = "Account Number stored in AccountId in DDB"
The end goal is to be able to get this into a lambda with an event bridge or something similar. Please note some accounts already have billing alarms set so it would only be for new accounts only. I appreciate any advice or input you may be able to assist me with, Thanks in advance.
I'm building basic reservation application with Flask.
I need to update Guests table rows with posted data from client side.
The user wants to update NAMESURNAME and IDENTITYNUMBER fields by specific res_id.
Here is my Guests model in models.py file
class Guests(Base):
__tablename__ = "GUESTS"
RESID = db.Column(db.Integer,db.ForeignKey("RESERVATION.ID"))
NAMESURNAME = db.Column(sqlite.VARCHAR(50))
IDENTITYNUMBER = db.Column(sqlite.VARCHAR(50))
This the function that is supposed to update guest info but I am building for loop wrong.How can I properly write this for loop.
def update_guests(request,res_id):
request = request.form.to_dict()
guests = db.session.query(Guests).filter(Guests.RESID == res_id).all()
for value,guest in zip(request.values(),guests):
guest.NAMESURNAME = value
guest.IDENTITYNUMBER = value
db.session.commit()
Also request object might be containing these key and values as an example.
Guest name and Guest identity number must be inserted into NAMESURNAME and IDENTITYNUMBER fields.
{"guest0" : "Name1", "identity0" : "245", "guest1" : "Name2" : "identity1" : "441"}
I a have a SQLite Database with:
first_name email password
Andrew t#t.com abcde
I am using this to check if there is a matching email and password:
if User.userManager.filter(email = postData['email'], password =
postData['password']):
name = User.userManager.filter(email = postData['email'], password = postData['password'])
print name.get('first_name')
return "success"
When I try to print first_name from the query i did above I get error 'too many values to unpack'
This is happening because get() method expecting for keyword arguments:
https://docs.djangoproject.com/en/1.11/ref/models/querysets/#get
The QuerySet returned by filter() method could contain more than one entry:
https://docs.djangoproject.com/en/1.11/ref/models/querysets/#filter
, so you should specify expected value for the requested field.
One of the ways to access this value is:
print name.get(first_name='Andrew').first_name
On the other hand, you could limit your filter query:
User.userManager.filter(email = postData['email'], password = postData['password'])[:1]
Or just use get() method straightway and access field value directly:
user = User.userManager.get(email = postData['email'], password = postData['password'])
print user.first_name
I need to find a person when he enters his mobile number or email in the login form.
My raw() query goes like this:
user = Users.objects.raw('SELECT * FROM main_users WHERE mobile = %s OR email = %s',[login_id],[login_id])
But I am always getting a error:
Exception Value: not enough arguments for format string
So, what's the correct format for getting this solved?
You should put parameters under the same list:
user = Users.objects.raw('SELECT * FROM main_users WHERE mobile = %s OR email = %s',
[mobile, email])
There is no need for a raw query here.
users = User.objects.filter(Q(mobile=login_id) | Q(email=login_id))
You can do this by any of these two ways as already said above:
from django.db.models import Q
users = User.objects.filter(Q(mobile=login_id) | Q(email=login_id))
or by using raw() method:
user = Users.objects.raw('SELECT * FROM main_users WHERE mobile = %s OR email = %s',[login_id,login_id])
The upper solutions were not working for me. I solved by this in Python 3
user = Users.objects.raw("SELECT * FROM main_users WHERE mobile = '%s' OR email = '%s' " %(mobile, email))
I am importing contacts from gmail. c_lst is the list that has the names and email address in a dictionary as follows - [{'name': u'fn1 ln1', 'emails': [u'email1#gmail.com']}, {'name': u'fn2 ln2', 'emails': [u'email2#gmail.com']},.
There are two problems with importing contacts:
Some of the contacts that I might be importing, might already be present in the database, in that case, I do not want to add another contact.
Unique usernames. There is a possibility of two emails being same, except the domain names. eg. email#gmail.com and then email#outlook.com in that case, I need to have distinct usernames so the first username would be like email, and the second one would be email1.
I have implemented both of them, and commented for making things clear.
Can there be more pythonic way of doing it?
for contact in c_lst:
email = contact.get('emails')[0]
name = contact.get('name').split(' ')
first_name, last_name = name[0], name[-1]
try:
# check if there is already a user, with that email address
# if yes then ignore.
u = Users.objects.get(email = email)
print "user exists"
except:
while True:
username = email.split('#')[0]
name, idx = username, 1
try:
# user with current username exists, so add numeral
Users.objects.get(username = username)
name = username + str(idx)
except User.DoesNotExist:
username = name
u = User.objects.create(username = username, email = email, first_name = first_name, last_name = last_name)
u.save()
break
Please let me know, of any other/better flow/approach.
For generating usernames, one might advice generating random numbers, but its okay for me
to go sequentially, as it is only one time activity.
The one thing I would like to change is to handle the first except explicitly. Since you are using:
u = Users.objects.get(email=email) # don't add space before and after "=" in argument
It could raise a MultipleObjectsReturned exception then create an infinite loop in the current except block.
So you should at least change your code to:
# ... your code ...
first_name, last_name = name[0], name[-1]
try:
u = Users.objects.get(email=email)
except User.DoesNotExist:
# ... your code ....
except User.MultipleObjectsReturned:
# handle this case differently ?
Well your might want to handle the second try except block similarly but that's your choice.
Hope this helps.