Using Google App Engine with python and their database, and trying to simply see if a given row already exists.
result = db.GqlQuery(
"SELECT phone WHERE phone = :1", self.request.get('phone'))
if result is not None:
self.response.status = 409
self.response.out.write(json.dumps({
"err": self.request.get('phone') + " is already subscribed."
}))
return
This does not seem to work, even though there is no row with a given phone number. Is result always not None?
result is an instance of GqlQuery, and will never be None. You're going to have to do something like iterate over it to see if you get results.
Related
I want to use python phonenumbers to get the number of digits that mobile phones have to have for each country.
I'm importing the phonenumbers/libphonenumber library.
I tried fetching the metadata with no success. Then I tried fetching an example number to then deduce it from there. It looks like I'm not being able to give with the adequate attributes or classes to fetch these. Do you know which are the attributes or classes I need to look for in order to get to this information?
country = phonenumbers.region_code_for_country_code(country_code)
metadata = phonenumbers.metadata_for_region(country)
or
region_code = phonenumbers.region_code_for_country_code(country_code)
example_number = phonenumbers.get_example_number_for_type(region_code, phonenumbers.PhoneNumberType.MOBILE)
I'm open to using other libraries too.
You can try this code that retrieves the required number of digits of a mobile phone number in a specific country using your database:
import sqlite3
def get_mobile_number_digits(country_code):
# Connect to the database
conn = sqlite3.connect("phone_number_format.db")
cursor = conn.cursor()
# Query the database for the required number of digits for the given country code
query = "SELECT num_digits FROM phone_number_format WHERE country_code=?"
cursor.execute(query, (country_code,))
result = cursor.fetchone()
# Close the database connection
cursor.close()
conn.close()
# Return the result
if result:
return result[0]
else:
return None
The database phone_number_format.db has a table named phone_number_format with columns country_code and num_digits. The get_mobile_number_digits function takes a country_code as input and returns the required number of digits for that country code. If the country code is not found in the database, the function returns None.
INTRO -
In the below python snippet,
I'm querying and fetching users' results from MySQL with the all(), then iterating the result and adding an address to a list of addresses related to a user, nothing special.
PROBLEM -
until now, I have always did it like this -
address = Address(...)
users = db.query(User).all()
for user in users :
user.addresses.append(address)
db.add(user)
db.commit()
so why when using the "SQL Expression Language" I need to iterate the result this way?
(when omitting the model notation it throws "Could not locate column in row for column")
stmt = select(User).join(Country, User.country_id == Country.id).where(Country.iso_code == iso_code).outerjoin(User.addresses)
related_users: Optional[List[User]] = db.execute(stmt).all()
if related_users:
address_in_db = self.get_or_create_address(...)
for user in related_users:
user.User.addresses.append(address_in_db ) # why this is not user.addresses.append(address)
db.add(user.User) # same here, why not just user
db.commit()
I think I have the right idea to solve this function, but I'm not sure why I get this error when I test it. Can anyone please help me fix this?
Error: conn = sqlite3.connect(db)
sqlite3.OperationalError: unable to open database file
Desired Output:
>>> get_locations(db, 'ANTA01H3F')
[('ANTA01H3F', 'LEC01', 'AA112'), ('ANTA01H3F', 'LEC01', 'SY110'), ('ANTA01H3F', 'LEC02', 'AC223')]
def get_locations(db, course):
'''Return the course, section and locations of the exam for the given course.'''
return run_query('''SELECT Courses.Course, Courses.Sections, Room.Locations
FROM Courses JOIN Locations ON Courses.ID = Locations.ID WHERE Course = ?''', [course])
This is too much abstract. ;)
See run_query() from where it is getting the value of db (sqlite database file name) to run queries. It is not getting correct file name that you are expecting.
You are calling the function wrong, it accepts db and sql statement string:
return run_query(db, "SELECT Courses.Course, Courses.Sections, Locations.Room " \
" FROM Courses JOIN Locations ON Courses.ID = Locations.ID WHERE Course = '{}'".format(course))
I am trying to check for a string that is being passed from a form in an html page. So the form picks up the user name and then checks the database if it already has been made. If it hasn't, it goes ahead and creates it. My errors are in the part of the logic that looks up that user name.
Note, I have commented out some areas where various errors have popped up:
import mysql.connector
import web
from mysql.connector import Error
import cgi, cgitb
cgitb.enable()
conn = mysql.connector.connect(host='localhost', database='database', user='root', password='root')
cursor = conn.cursor()
form = cgi.FieldStorage()
username = form.getvalue('username')
password = form.getvalue('password')
# check_existence = """
# SELECT username FROM members WHERE username = '%s'
# """
check_existence = """
SELECT username FROM members WHERE username = %s
"""
# cursor.execute(check_existence, username)
# "Wrong number of arguments during string formatting")
cursor.execute(check_existence, (username))
# ^pushes down to con.commit
# cursor.execute(check_existence, (username,))
# ^wrpmg number of arguments during string formatting
# with comma, the error is in commit, with comma, its in execute
conn.commit()
matches = cursor.rowcount()
Now the error is pointing to conn.commit. Though this is depending on the syntax, sometimes it points to the line above it.
Error:
=> 203 conn.commit()
<class 'mysql.connector.errors.InternalError'>: Unread result found.
args = (-1, 'Unread result found.', None)
errno = -1
message = ''
msg = 'Unread result found.'
In my limited experience, commit() is only used to save (commit) updates to the database. It looks like you're executing a select query, but doing nothing with the results, and the error is related to that. Try moving the commit to the end, or doing away with it. Try using/doing something with the results stored in the cursor. I believe the latter is the solution.
The .commit method was off to a start but it wasn't the only problem with the code. I had two problems though one of them is not posted in the original post, I will explain both.
A) cursor.rowcount returns -1. Not sure why but it does. My understanding of it was that it will return the number of rows. But you can use cursor.fetchall() instead. This will return matches in an array....but if the array is empty, it'll return an empty array.
So I used this logic:
if not(cursor.fetchall()):
the set/array is empty>> Create user
else:
something was found >>dont create user
B) This was in the rest of my code. I was checking if the connection was connected:
if conn.is_connected():
The problem with doing this is that if you do this after a .execute, it will return false. So I put it higher up in the logic, to check right when it attempts to connect to the database.
I'm trying to make a function where that returns the name of the logged in user if one can be identified or None if not. i want to do this by finding the session id from the cookie in the Bottle request if present, and using it to look up the user in the sessions table.
My code so far:
def session_user(db):
"""try to
retrieve the user from the sessions table
return usernick or None if no valid session is present
"""
cursor = db.cursor()
sessionid = bottle.request.get_cookie(COOKIE_NAME)
usernick = None
if sessionid:
cursor.execute("SELECT usernick FROM sessions WHERE sessionid=?", (sessionid,))
usernick = cursor.fetchall()
return usernick
The table in database:
DROP TABLE IF EXISTS sessions;
CREATE TABLE sessions (
sessionid text unique primary key,
usernick text,
FOREIGN KEY(usernick) REFERENCES users(nick)
);
When i use the current code in my function i get a unit test error:
line 125, in test_session_user
self.assertEqual(nick_from_cookie, None, "Expected None in case with invalid session id, got %s" % str(nick_from_cookie))
AssertionError: [] != None : Expected None in case with invalid session id, got []
See the cursor.fetchall documentation:
Fetches all (remaining) rows of a query result, returning a list. Note that the cursor’s arraysize attribute can affect the performance of this operation. An empty list is returned when no rows are available.
Since an empty list in Python is a false-y expression this normally works out well - when not doing explicit compares with False/None. Always returning a list also makes code that iterates the result set (or checks the length) easier because no special case for None has to be done.
Use the aptly named fetchone to get a single result record, or None.