I'm trying to make a registration module to use in a larger login/authentication program and I need to make a function that can check if a username already exists in a collection.
I haven't tried much more than this, this is my first real programming project and I'm stuck on this part. I realize I could use in-line dictionary databases, but I want to learn how to integrate 3rd party databases with my programming.
from pymongo import MongoClient
import time
client = MongoClient('localhost', 27017)
loginDB = client["loginDB"]
userCol = loginDB["userCol"]
##Username##
print('Choose A Unique Username')
time.sleep(1.2)
unameInput = input("Enter Username: ")
unameList = {'Username': unameInput}
unameQuery = {}
unameQuery2 = userCol.find_one({'Username.Username': {'$gt': 'a'}})
if unameInput != unameQuery2:
print('Name is Available | Accepted!')
allList = {'Username': unameList}
userCol.insert_one(allList)
else:
print('Sorry, Please Try Again.')`
The expected result is to search the database for everything that starts with the letter "a", forward. If the input (unameInput) does not equal anything in the query result (unameQuery2), then print "Username is available". If anything in the query matches the input, then print "Please try again", however, it's accepting everything that is input and exiting the code.
You are using find_one() to find one entry in Username and then checking if unameInput is equal to it. If it's not an exact match, it will execute the code for name is available.
Try find() instead as this will iterate over all the documents in the collection.
unameQuery2 = userCol.find()
if unameInput not in unameQuery2:
# do something
I figured it out, I was putting dictionaries inside of dictionaries inside of documents, as well as not iterating "allList".
Related
I am trying to do a password saver, where users can insert a password and it will save to a computer. I started with
password = str(input("What is your password that you want to save?"))
url = str(input("Which is the site that you want your password to save to?"))
password_saved = {url : password}
with open('password_saved', 'wb') as password_saved_file:
pickle.dump(password_saved, password_saved_file)
print(password_saved)
However, password_saved = {url:password} resets the whole dictionary in to that one, so if you run it, it will just resets to only one, insead of saving all of it. So, I tried to replace it with:
password_saved[url] = password
But, then, it will say it is not defined. How can I define the dictionary without making any changes to it, including blank-spacing it?
Actually, your code is all fine. But, if you put in the same value 2 times, it won't show. Make sure to try different URLs for each one to make sure that everything works.
First, declare a dictionary then pass index and value to the dictionary.
password_saved = {}
password_saved[url] = password
when you say "it" is not defined, do you mean the dictionary? If so, this could just be a problem of initializing it before you call it. Right now, you are creating a new dictionary named "password_saved" with only one entry. It should look something like
password_saved = {}
...
password = str(input("What is your password that you want to save?"))
url = str(input("Which is the site that you want your password to save to?"))
password_saved[url] = password
with open('password_saved', 'wb') as password_saved_file:
pickle.dump(password_saved, password_saved_file)
print(password_saved)
I'm really running out of ideas.
I recently was assigned to improve a script we have in Python so that it can fetch all users whose email match a string (more exactly, all the users whose email match with the value obtained from a HTML's text input).
It works well by using this filter ("search" is the text obtained from the text input):
user_filter = '(mail=%s)' % search
but it needs for the email value to be exactly so it can match with the user's email, and what I need is to match any written down value(string).
The last filter I used was this:
user_filter = '(mail=*%s*)' % search
and also like this:
user_filter = '(mail=%s*)' % search
(please notice the use of wildcards)
but none of them worked.
Any ideas who can I achieve this? Do you need more context?
I'm using ldap and function search_s
This is a snippet of the code:
def ldap_query(query):
""" returns the members of an LDAP group """
try:
ldap_conn = ldap.initialize(LDAP_URL)
ldap_conn.timeout = LDAP_TIMEOUT
ldap_conn.simple_bind(LDAP_USERNAME, LDAP_PASSWORD)
if not ldap_conn.whoami_s():
raise Exception('503 Unable to authenticate to LDAP server with master user & password')
res = ldap_conn.search_s(LDAP_BASE_DN, ldap.SCOPE_SUBTREE, query)
if res == []:
raise Exception('Group not found in LDAP directory, using filter {}'.format(query))
print res
And I'm using it like this:
print ldap_query('(mail=my.name#mycompany.com)')
but if I use the wildcards, I ended up with the error:
print ldap_query('(mail=a.name*)')
EDITED
just now it started to work, by using the last filter (the one just above here). Dunno why it didn't work before.
It worked well by using just one wildcard:
'(mail=a.name*)
rather than two:
'(mail=*a.name*)
I used that approach because of what I've seen while working with MysQL "LIKE" query %string%, whereas with LDAP filters seems not to be the case.
I recently started to develop with odoo8 and I've met a problem.
My problem is that I have two classes : 'helpdesk' and 'res_partner' and I don't know why my code stuck for a long time when I create a new record in 'res_partner' but when I comment this block of codes (below) my code works great.
self.env['res.partner'].create({
'name': nameFmt,
'firstname': self.firstNameOfUser.strip().lower().title(),
'lastname': self.lastNameOfUser.strip().upper(),
'birthdate': newDateFmt,
'birth_place': self.pBirthOfUser,
'is_company': False
})
'helpdesk' class has several fields and methods to get information, and computes them from the user inputs. Once the information computed, I create my record which is a new partner.
How I tried to solve my problem, I :
Launched odoo in shell mode with '--debug' option and a pdb where the code is stuck (it's stuck at the 'create' method as I said)
Read some threads and documentations about my problem, but most are in v7 for the create method and anybody has been stuck like this for the creation of a record
Checked each value that I sent to create my new record
Saw the behavior of records and how they are stored with phpPgAdmin
For more information, this is my entire method definition :
#api.one
def addPartnerInDB(self):
if (not self.firstNameOfUser or
not self.lastNameOfUser or
not self.dobOfUser or
not self.pBirthOfUser):
raise ValidationError(u"Tous les champs sp\u00E9cifi\u00E9s pour "
u"cette demande doivent \u00EAtre remplis !")
# Avoid concurrent drop-down
self.dropDownList1 = False
self.dropDownList3 = False
# Get every partners
listOfPartners = self.env['res.partner'].search(
[
('is_company', '=', False)
]
)
# Avoid useless compute for each iteration
newDateFmt = u"".join(datetime.datetime\
.strptime(str(self.dobOfUser), "%Y-%m-%d")\
.strftime("%d/%m/%Y"))
newFNameFmt = self.firstNameOfUser.strip().replace(" ", "-").lower()
newLNameFmt = self.lastNameOfUser.strip().replace(" ", "-").lower()
newBPFmt = self.pBirthOfUser.strip().replace(" ", "-").lower()
matchedPartners = []
# Fetch partner specified by the user
for p in listOfPartners:
if (newFNameFmt == p.firstname.strip().replace(" ", "-").lower() and
newLNameFmt == p.lastname.strip().replace(" ", "-").lower()):
matchedPartners.append(p)
partnerAlreadyExist = False
# If the list is not empty, then the fetch is enhance
if (matchedPartners):
for m in matchedPartners:
partnerDOB = False
partnerBP = False
if (not isinstance(m.birthdate, bool)):
if (newDateFmt == m.birthdate):
partnerDOB = True
if (not isinstance(m.birth_place, bool)):
if ((newBPFmt
== m.birth_place.strip().replace(" ", "-").lower())):
partnerBP = True
# If one of them it's true, the user already exist
if (partnerDOB or partnerBP):
partnerAlreadyExist = True
# Avoid useless iteration
break
# If the user specified doesn't exist he's created
if (not partnerAlreadyExist):
# Encode the string to avoid UnicodeError and further string errors
nameFmt = (self.lastNameOfUser.strip().upper(),
+ u" "
+ self.firstNameOfUser.strip().lower().title())
self.env['res.partner'].create(
{
'name': nameFmt,
'firstname': self.firstNameOfUser.strip().lower().title(),
'lastname': self.lastNameOfUser.strip().upper(),
'birthdate': newDateFmt,
'birth_place': self.pBirthOfUser,
'is_company': False
}
)
else:
raise ValidationError(u"L'utilisateur renseign\u00E9 "
u"existe d\u00E9j\u00E0 !")
EDIT
After several attempts to debug my code with pdb, I noticed that something went wrong in the for statement when I compare firstnames and lastnames :
for p in listOfPartners:
if (newFNameFmt == p.firstname.strip().replace(" ", "-").lower()
and newLNameFmt == p.lastname.strip().replace(" ", "-").lower()):
# Append element
Indeed, pdb blocks (2/3 sec) for each start of for statement before it gives me the hand back.
For example :
(pdb) ->if (newFNameFmt == p.firstname.strip().replace(" ", "-").lower() and
# stuck 2-3 seconds
(pdb) -> newLNameFmt == p.lastname.strip().replace(" ", "-").lower()):
This behavior continues for about the first iterations of the for statement, after this amount of iterations, this behavior is no longer adopted for the rest of the iterations. Once I arrived at the create statement (with pdb), the creation record is miraculously unlocked and the code works.
I still don't know why this problem occurs and I still don't know how to solve it.
you got that issue because maybe you have compare 2 different type! In your case, you maybe try to compare between res_partner object and string type or another! That should be res.partner(2973,).id or res.partner(2973,).name ....
I've found an answer for my question, and I think to know where the problem came from.
Where was my problem
So the problem came from my first for statement which is :
listOfPartners = self.env['res.partner'].search(
[
('is_company', '=', False)
]
)
for p in listOfPartners:
if (newFNameFmt == p.firstname.strip().replace(" ", "-").lower()
and newLNameFmt == p.lastname.strip().replace(" ", "-").lower()):
matchedPartners.append(p)
Theoretically nothing could be wrong with the for and search statements since they do what I want to do. But the problem is that each iteration that the program did in this for was 'n' queries sent to the PostgresSQL server (where n corresponds to the number of time that p is used in each iteration. In my case n = 2). This issue escalated quickly since search returned me about a thousand of partners (which are represented by id of each record saved in res.partner that matched the search query). So in the for this corresponds to thousands of queries that I sent in a very short time to the PostgreSQL server, and it seems that this server couldn't handle this amount of requests in a very short time.
So the problem was not the code in himself, but the behavior that I gave to him. The result of that behavior gave another behavior to the PostgreSQL for the further queries that I will give via Odoo, like create.
How I solved it
The solution for me was to use the psycopg2 module. This module allowing communication with the postgreSQL server. The main difference between both in my case was that Odoo stayed in communication with the PostgreSQL server even if I used search to get only values that I wanted. While psycopg2 gived me a list (of tuples) that only contains "real" values and not an id like Odoo gave me with search.
Once again, I don't know if the solution that I choosed was the best or if the issue came from there like I said above but this solution works well for me and I hope it will help others users stuck in a problem with the same behavior.
I am writing a Django-based back end using django-mongodb-engine for an android app and I'm trying to get data from a PUT request to update a record in my database. I'm getting a username and filtering the database for the user object with that name (successfully), but the save function doesn't seem to be saving the changes. I can tell the changes aren't being saved because when I go onto mLab's online database management tool the changes aren't there.
Here's the code:
existing_user = User.objects.filter(userName = user_name)
if existing_user == None:
response_string += "<error>User not identified: </error>"
elif (existing_user[0].password != user_pwd):
response_string += "<error>Password error.</error>"
#if we have a validated user, then manipulate user data
else:
existing_user[0].star_list.append(new_star)
existing_user[0].save()
I'm not getting any error messages, but the data remains the same. The star_list remains empty after the above. In fact, as a test I even tried replacing the else clause above with:
else:
existing_user[0].userName = "Barney"
existing_user[0].save()
And following this call, the existing_user[0].userName is still it's original value ("Fred", rather than "Barney")!
Found an answer to this question. I'm not sure why it wasn't working as posted, but there were problems trying to access the object through the list... in other words the following didn't work:
existing_user[0].userName = "Barney"
existing_user[0].save()
But this did:
found_user = existing_user[0]
found_user.userName = "Barney"
found_user.save()
Based on my understanding of Python lists, either one should be the same... but maybe some python genius out there can explain why they aren't?
I'm building a text game and need to store 2 things in a single variable: a string, and a request for input. Note that I don't mean to store the output of the request - I mean that if the variable is called, both the string and the request itself are printed, after which the user answers the request.
raw_input("Do you do X or Y?") therefore doesn't work for me, because I need to store the request before I deploy it.
Some background about my approach:
Everything's stored in a dictionary, where the keys are the user's current location and the values are possible choices:
dict = {location1: (location2, location3), location2: (location1, location4)...}
So, I'll print location1, which will simultaneously print the string that describes that location, and make a request for input. The input triggers the program to print the next appropriate location, and the program keeps on going.
I'm trying to work out a recursive function that does this.
For each location, the request for input is worded differently, which is why I don't just build the request into my recursive function.
Sidenote: if anyone has any other suggestions/different approaches I should use instead, please share those too!
For each location, the request for input is worded differently,
Simply create another dictionary for input request corresponding to each location. For ex:
requests_dict = {
'location1': 'Please enter xxx: ',
'location2': 'Do you do X or Y: ', # and so on
}
Then use that dict to print the request.
user_input = raw_input(requests_dict['location2'])
Of course, you would like to make the last code based on some logic so that which one of that dicts is called, but I think you get the idea.
Update:
responses_dict = {}
user_input = raw_input(requests_dict['location2'])
responses_dict[user_input] = 'You are in %s' % user_input