Flask/Rest Get a string from another web service - python

I have two web services called getCourseCodeWS and checkStudentOnCourseWS both with 1 corresponding DB. The first WS returns a courseCode from a DB. This courseCode should work as a parameter in my checkStudentOnCourseWS which should use the courseCode + another parameter called personalIdentityNumber, which I get from checkStudentOnCourseWS's DB. This should return a true/false depending on if the arguments match the database, in other words, if the student appears in the course.
My question is how do I request the actual respons I get from my getCourseCodeWS to work as an argument for checkStudentOnCourseWS?
#app.route('/courses/<course>/<period>', methods= ["GET"])
def checkCourseCodeWS(course, period):
myCursor2 = mydb.cursor()
query2 = ("SELECT courseCode FROM paraplyet.courseInfo WHERE courseName = " + "'" + course + "' AND duration = " + "'" + period + "'")
myCursor2.execute(query2)
myresult2 = myCursor2.fetchall()
return jsonify(myresult2)

Related

How to implement a combination search?

I am working on an API endpoint (Python + Sqlite) that runs a SQL query based on the following parameters: race, gender, age, location. The caveat, however, is that all of these parameters are optional and any combination of the parameters is valid. For example, the following requests are all valid.
localhost:8000/api?age=10&gender=M
localhost:8000/api?race=Asian&age=3&location=US&gender=F
localhost:8000/api
I'm not sure how to best approach this. It seems like a simple logic puzzle, but I can't seem to wrap my head around it. The only difference between all of these would be the "Where" statement in the SQL query.
Any advice or related ideas I could look into would be appreciated. Sorry if I didn't explain the problem clearly, I am struggling to even articulate the issue. Thanks.
What you can do is construct the SQL query based on the parameters received in the incoming request.
Simple pseudo code :
SQLquery = "SELECT * FROM mytable "
if there are any parameters
SQLquery = SQLquery + "WHERE "
any more parameters?
SQLquery = SQLquery + " and "
if input request has age
SQLquery = SQLquery + "age = " + agevalue
any more parameters?
SQLquery = SQLquery + " and "
if input request has race
SQLquery = SQLquery + "race = " + racevalue
any more parameters?
SQLquery = SQLquery + " and "
if input request has gender
SQLquery = SQLquery + "gender = " + gendervalue
any more parameters?
SQLquery = SQLquery + " and "
if input request has location
SQLquery = SQLquery + "location = " + locationvalue
Use SQLquery to fetch data from database

Databasing a float Python - TypeError: coercing to Unicode: need string or buffer, float found

I am currently having trouble trying to insert a float into my sql query, the value is pulled from a api and is normally a very exact number, I cannot get python to insert into my database with said float, I have even tried rounding it down but it is still throwing errors. Here is the errors as well as code:
Error
Traceback (most recent call last):
File "main.py", line 12, in <module>
ic.main()
File "/home/sage/Dev/market_Mon/interface_Controller.py", line 32, in main
ccr.config_Load_Cur()
File "/home/sage/Dev/market_Mon/config_Controller_Rebuild.py", line 41, in config_Load_Cur
dbc.database_Insert(str(arr[0]), str(arr[0]), str(arr[1]), arr[2], time.time())
File "/home/sage/Dev/market_Mon/database_Controller.py", line 14, in database_Insert
query = "INSERT INTO " + '`'+ table + '`' + " VALUES('`id` INTEGER PRIMARY KEY','" + ticker + "', '" + currency + "', '" + exchange + "', '" + date + "')"
TypeError: coercing to Unicode: need string or buffer, float found
Code:
Arr[2] is the value which is returning a float. Note that I've removed all my attempts at resolving this issue because they just get in the way of being able to see exactly how it works.
from decimal import Decimal, ROUND_HALF_UP
import ConfigParser
import io
import json_Controller as jsc
import database_Controller as dbc
import time
from colorama import init, Fore, Back, Style
import threading
import re
import json
from sys import stdout
#Function used to add new currency tickers into config.ini
def config_Add_Cur(currency):
conf = open('config.ini', w)
config = ConfigParser.ConfigParser()
config.add('currency', currency, True)
print (currency + 'added to config.ini')
#Function used to load all currency data from config.ini and to pull current
#Market data related to the relative tickers
def config_Load_Cur():
api_Key = '967OAAEVKJ9WT8F1'
arr = []
whilel = 1
var = 1
with open('config.ini') as f:
conf = f.read()
config = ConfigParser.RawConfigParser(allow_no_value=True)
config.readfp(io.BytesIO(conf))
while whilel == 1:
for (each_key, each_val) in config.items('currency'):
try:
currency = each_key
data = jsc.json_Import_Cur(currency, api_Key)
arr.insert(0, data['Realtime Currency Exchange Rate']['3. To_Currency Code'])
arr.insert(1, data['Realtime Currency Exchange Rate']['4. To_Currency Name'])
arr.insert(2, data['Realtime Currency Exchange Rate']['5. Exchange Rate'])
arr.insert(3, data['Realtime Currency Exchange Rate']['6. Last Refreshed'])
dbc.database_Insert(str(arr[0]), str(arr[0]), str(arr[1]), arr[2], time.time())
print (Fore.GREEN + "-------------------------------------------------------------------------------------------")
print (Back.WHITE + Style.DIM + Fore.CYAN + arr[0] + Style.NORMAL + Fore.YELLOW + arr[1] + Fore.MAGENTA + Back.WHITE + arr[2] + Fore.RED + Back.WHITE + arr[3] + Fore.BLUE + Back.WHITE +" inserted into database" + Style.RESET_ALL)
if var == 4:
print(Fore.GREEN + "-------------------------------------------------------------------------------------------")
print (Back.WHITE + Fore.RED + "Sleeping 60 Seconds" + Style.RESET_ALL)
time.sleep(60)
var = 1
else:
var = var + 1
except(KeyError):
pass
Database Controller:
import sqlite3
from colorama import init
#Initializes database connection and returns connection to function caller
def database_Connect():
connection = sqlite3.connect('cur_Monitor.db')
return connection
#Inserts new rows into a table, this is created to ensure uniformity between rows
def database_Insert(table, ticker, currency, exchange, date ):
try:
sql = database_Connect()
query = "INSERT INTO " + '`'+ table + '`' + " VALUES('`id` INTEGER PRIMARY KEY','" + ticker + "', '" + currency + "', '" + exchange + "', '" + date + "')"
sql.execute(query)
sql.commit()
except():
pass
print "Error occurred databasing!"
#Queries the table, and returns all values which either match or include the
#name string in their overall value
def database_Read(table, currency):
sql = database_Connect()
query = "SELECT * FROM " + table + " WHERE currency LIKE '" + currency + "%'"
for row in sql.execute(query):
return row
#Creates new tables into the database, this will always use the same format
#to ensure uniformity between tables
def database_Table(name):
sql = database_Connect()
query = "CREATE TABLE `" + name + "` (`id` INTEGER PRIMARY KEY,`ticker` text , `currency` text, `exchange` float, `date` timestamp)"
sql.execute(query)
sql.commit()
print name + " New table created!"
#Allows the ordering of table read outs to help allow users to view data better
def database_Order(table, order):
sql = database_Connect()
query = "SELECT * FROM " + table + " ORDER BY " + order
for row in sql.execute(query):
print row
It looks as though you may not have cast your exchange rate into a string before concatenating it with the rest of your SQL query. You do this for the other values in dbc.database_Insert but not for the exchange rate

I keep getting list out of range trying to convert mysqldatabase into html

I dont get why it keeps giving me the list out of range error for sys.argv[1]. From my understanding I am passing data to user_database. Help please
import sys, MySQLdb
def PrintFields(database, table):
host = 'localhost'
user = 'root'
password = 'boysnblue1'
conn = MySQLdb.Connection(db=parking_report, host=localhost, user=root, passwd=boysnblue1)
mysql = conn.cursor()
sql = """ SHOW COLUMNS FROM %s """ % table
mysql.execute("select id, date, time, status, from report_table ")
fields=mysql.fetchall()
print '<table border="0"><tr><th>order</th><th>name</th><th>type</th><th>description</th></tr>'
print '<tbody>'
counter = 0
for field in fields:
counter = counter + 1
id = field[0]
date = field[1]
time = field[2]
status = field[3]
print '<tr><td>' + str(counter) + '</td><td>' + id + '</td><td>' + date + '</td><td>' + time + '</td><td>' + status + ' </td></tr>'
print '</tbody>'
print '</table>'
mysql.close()
conn.close()
users_database = sys.argv[1]
users_table = sys.argv[2]
print "Wikified HTML for " + users_database + "." + users_table
print "========================"
PrintFields(users_database, users_table)
sys.argv is a list containing the name of the program's file and all of the arguments it was passed on the command line.
If you run python script2.py, the contents of sys.argv will be ['script2.py'].
If you run python script2.py database_name table_name, the contents of sys.argv will be ['script2.py', 'database_name', 'table_name'], which is what your program is currently configured to expect:
users_database = sys.argv[1]
users_table = sys.argv[2]
Since you are calling it the first way, sys.argv[1] does not exist, and you get your error that the index (1) is out of range (it only goes to 0).

Python script returns old MySQL values (until restart) [duplicate]

This question already has answers here:
Why are some mysql connections selecting old data the mysql database after a delete + insert?
(2 answers)
Closed 7 years ago.
I have the following code that I run once and then again when a new value is inserted to refresh.
def getStageAdditives(self, stage):
stagesAdditivesSelectQuery = """SELECT a.id,
a.name,
IFNULL(sa.dose, 0) as dose,
IFNULL(sa.last_dose, 0) as last
FROM additives a
LEFT JOIN stage_additives sa
ON a.id = sa.additive_id
AND sa.stage_id = (
SELECT id
FROM stages
WHERE name = '""" + stage + """')
ORDER BY a.name"""
self.cursor.execute(stagesAdditivesSelectQuery)
data = self.cursor.fetchall()
additives = []
for additive in data:
id = additive[0]
name = additive[1]
dose = additive[2]
last = additive[3]
additives.append({ 'title': name, 'dose': dose, 'last': last })
print stagesAdditivesSelectQuery
return additives
The issue is that after I use the following code to insert a value into 'additives' table I get old values (new value is missing).
def createAdditive(self, name):
additiveInsertQuery = """ INSERT INTO additives
SET name = '""" + name + """'"""
try:
self.cursor.execute(additiveInsertQuery)
self.db.commit()
return "True"
except:
self.db.rollback()
return "False"
I can confirm that values are being inserted into the database by looking at phpMyAdmin. If I restart the script I get the new values as expected. If I run the query with phpMyAdmin that also returns new values. Refreshing the page and waiting 10+ seconds doesn't help and I get old values still.
Both methods are in separate classes/files if it matters. The getStageAdditives is called with ajax after the 'createAdditive' method has returned successfully.
DB initialisation:
import MySQLdb
import time
class Stage:
def __init__(self):
self.db = MySQLdb.connect('192.168.0.100', 'user', 'pass', 'dbname')
self.cursor = self.db.cursor()
Another method that retrieves similar values gets the new values as expected (same class as createAdditives):
def getAdditives(self, additive=None):
where = ''
if additive is not None:
where = "WHERE pa.additive_id = ("
where += "SELECT id FROM additives "
where += "WHERE name = '" + additive + "') "
where += "AND a.name = '" + additive + "'"
additiveSelectQuery = """ SELECT a.name,
pa.pump_id
FROM additives a,
pump_additives pa """ + where + """
ORDER BY a.name"""
self.cursor.execute(additiveSelectQuery)
data = self.cursor.fetchall()
additives = []
for item in data:
additives.append( {'additive': item[0], 'pump': item[1]} )
return additives
For those who find this question: Similar question was solved in Why are some mysql connections selecting old data the mysql database after a delete + insert?
The trick is to add an connection.commit().

Python - update database

How would I update an entry that is already in a database using sqlite3?
I've tried:
db_curs.execute("INSERT INTO `database` (cID) VALUES ('Updated')")
But this, of course, creates a new entry. I can obtain the (line(?)) number (of the entry) and what is the command to update the database rather than create a new entry?
EDIT:
Put a bit better, when I convert the SQL entry to a python list I get the following,
(1, u'GGS-04', u'John', u'Smith', 9, u'0')
I need to be able to add a digit to the last item. Here is what I have.
info = (1, u'GGS-04', u'John', u'Smith', 9, u'0')
for result in info:
ln = str(result[0])
ggs = str(result[1])
first_name = str(result[2])
last_name = str(result[3])
dob = str(result[4])
spend = str(result[5])
while True:
res = raw_input("Enter points to add: ")
try:
int(res)
break
except:
print "Please enter a number..."
pass
spend = str(int(spend) + int(res))
db_curs.execute("UPDATE `" + db_name + "` (cID, first_name, last_name, date_of_birth, spend) VALUES ('" + srce + "', '" + first_name + "', '" + last_name + "', '" + dob + "' WHERE '" + spend + "')")
db_connection.commit()
Could someone please explain the correct syntax for this command? It would be awesome if I could just update the "Spend" column than having to update them all from prefixed variables.
Thank you :)
This shall work:
db_curs.execute("UPDATE database SET spend =`" + spend + "` WHERE cID="+ cID)
See also SQL Update Syntax
Btw, "database" isn't a useful name for a database's table. What about "users" or "spendtime" or sth more descriptive?

Categories

Resources