How to get a value from SQLite to convert it? - python

So I have an issue, I am trying to convert a float value from SQLite Db.
The value represents a price in USD and I want to convert it in BTC, I was installing python-forex but because I do not have experience enough I am stack on this:
b = BtcConverter(force_decimal=True)
p = float(acf1.p1)
pbtc = b.convert_to_btc(10, 'USD')
What I need to do is to exchange "10" with "p", and "p" is a row from my SQlite Db.
I was trying to get acfi.p1 from db table with:
acf1 = KAch.query.order_by(KAch.reg.desc()).all()
As well the html code is:
{{ "%.9f" %pbtc }}
But because I am new is giving me 500 error.
Could you give me a hint?
Update:
#app.route('/adfa', methods=['GET', 'POST'])
def add_foa():
t1=request.form.get('t1')
c1=request.form.get('c1')
p1=request.form.get('p1')
p2=request.form.get('p2')
um1=request.form.get('um1')
ce1=request.form.get('ce1')
dc1=request.form.get('dc1')
mdla1=request.form.get('mdla1')
mdam1=request.form.get('mdam1')
aop=request.form.get('aop')
pz1=request.form.get('pz1')
users_id = request.form.get('users_id')
acf1 = KAch(
t1=t1,
c1=c1,
p1=p1,
p2=p2,
um1=um1,
ce1=ce1,
dc1=dc1,
mdla1=mdla1,
mdam1=mdam1,
aop=aop,
pz1=pz1,
users_id=current_user.id,
reg=datetime.now())
db.session.add(acf1)
db.session.commit()
return redirect(url_for('adfa', users_id=current_user.id, _external=True))
#app.route('/profil/<int:users_id>')
#login_required
def profil(users_id):
ac1 = KAch.query.order_by(KAch.reg.desc()).all()
user = User.query.filter_by(id=users_id).first()
profil1 = KProfil.query.filter_by(id=users_id).one()
b = BtcConverter(force_decimal=True)
#p = float(acf1.p1)
pbtc = b.convert_to_btc(10, 'USD')
if 'out' in current_user.tc:
return redirect(url_for('adpro', users_id=current_user.id, _external=True))
elif 'n' in current_user.tc:
return redirect(url_for('logout', _external=True))
return render_template('front/usr/usr.html', profil1=profil1, user=user, ac1=ac1, pbtc=pbtc)

The Solution I found it is easy and is working!
Server side:
b = BtcConverter(force_decimal=True)
p1btc = b.get_latest_price('USD')
p1btcr = b.get_latest_price('RON')
pbtc = b.convert_to_btc(10, 'USD')
pron = float(Decimal(p1btcr))
HTML side:
{{ acf1.p1 / pron }}

Related

HTML flask To accept only integer input

I'm trying to accept only integer input using the int() function and the type to number with min set. But I noticed that when I give an input like 5.0 it should treat it as an invalid input and accept only integers.
<input autocomplete="off" class="form-control" min="0" name="shares" id="shares" placeholder="Shares" type="number">
def sell():
"""Sell shares of stock"""
rows = db.execute("SELECT * FROM tracker WHERE id=:id", id = session["user_id"])
if request.method == "GET":
return render_template("sell.html", rows = rows)
else:
symbol = request.form.get("symbol")
shares = request.form.get("shares")
if not shares:
return apology("missing shares",400)
if not symbol:
return apology("missing symbol",400)
lis = db.execute("SELECT * FROM tracker WHERE id=:id AND name=:name", id=session["user_id"], name=symbol)
share = int(shares)
if lis[0]["no"] < share:
return apology("too many shares",400)
price = lookup(symbol)["price"]
cost = price * share;
saving = db.execute("SELECT cash FROM users WHERE id=:id", id=session["user_id"])[0]["cash"]
db.execute("UPDATE users SET cash=:cash WHERE id=:id", cash=cost + saving, id=session["user_id"])
if lis[0]["no"] == share:
db.execute("DELETE FROM tracker WHERE id=:id AND name=:name", id=session["user_id"], name=symbol)
else:
db.execute("UPDATE tracker SET no=:no where id=:id AND name=:name",no=lis[0]["no"] - share,id=session["user_id"], name=symbol)
db.execute("UPDATE users SET cash=:cash WHERE id=:id", cash=saving+cost, id=session["user_id"])
flash("Sold!")
return redirect("/")
I dont' see the error code,however I guess is caused by the html input.
UPDATE
Try this:
<input autocomplete="off" class="form-control" step="0" name="shares" id="shares" placeholder="Shares" type="number">
UPDATED:
Obviously you can instead run the check in Python, by doing something like:
symbol = request.form.get("symbol")
shares = request.form.get("shares")
if not symbol:
return apology("missing symbol",400)
if shares:
try:
shares = int(shares)
except ValueError:
error = 'It must be an integer'
return redirect("/", error=error)
else:
return apology("missing shares",400)
lis = db.execute("SELECT * FROM tracker WHERE id=:id AND name=:name", id=session["user_id"], name=symbol)
if lis[0]["no"] < share:
return apology("too many shares",400)
(For reference i leave the older answer)
Which won't work because shares would be a string
shares = intrequest.form.get("shares")
if isinstance(shares, float)):
error = 'It must be an integer'
return redirect("/", error=error)
This will work because first it checks if is a float or not, if it is then it will redirect , else you turn it a

Flask Select Field Form Registers as None

I am immensely baffled by what should be very simple in my forms as I have this same construct working in other areas of my Flask web application. Below is a route I have:
#data_tools.route('/dataTools', methods=['POST', 'GET'])
def data_tools_upload():
table = '<table></table>'
result = '<table></table>'
message = ''
var2use = None
vars = ''
dt_name = ''
dtRadios = dtFormRadio(request.form)
bins = 5
foo=''
if request.method == 'POST':
tmp_filename = tempfile.gettempdir()+'\\input.csv'
if request.files:
to_upload = request.files.get('file')
dt_name = str(to_upload).split()[1]
if to_upload:
f = request.files['file']
f.save(tmp_filename)
if os.path.exists(tmp_filename):
orig_df = pd.read_csv(tmp_filename)
vars = list(orig_df.columns)
## Testing new form part
#dtRadios.varlist.choices = vars
foo = dtRadios.varlist.data
## end test
var2use = request.form.get("var2use")
if var2use != None:
indx = vars.index(var2use)
if dtRadios.dtRadioList.data == 'descriptives':
result = dt.get_descriptives(orig_df[vars[indx]])
if dtRadios.dtRadioList.data == 'percentiles':
result = dt.get_percentiles(orig_df[vars[indx]])
if dtRadios.dtRadioList.data == 'frequency':
if dtRadios.binSize.data != None:
bins = dtRadios.binSize.data
result = dt.get_frequency(orig_df[vars[indx]], bins = bins)
result = pd.DataFrame.from_dict(result, orient='index', columns = [var2use]).to_html(classes='table table-striped table-hover', header = "true", justify = "center")
dims = orig_df.shape
message = 'Data file %s with %s rows and %s columns loaded.' % (dt_name, dims[0],dims[1])
table = orig_df.head(10).to_html(classes='data', header = "true")
return render_template('dataTools.html', results = [result], message = message, vars = vars, var_name = var2use, dtForm=dtRadios, foo=foo)
and then here is a form I have built to go along with this
class dtFormRadio(FlaskForm):
dtRadioList = RadioField('Choose Option:', choices=[('descriptives','Get Descriptives'),
('percentiles','Get Percentiles'), ('frequency','Get Frequency')])
#varlist = SelectField('Choose a variable', [DataRequired()], coerce=str)
varlist = SelectField('Choose a Variable', choices=[('clean', 'Clean/Processed Text'),('original', 'Original Text String')])
binSize = IntegerField('Bin Size', [DataRequired()], default = 10)
The relevant part of my question surrounds this line foo = dtRadios.varlist.data. It always evaluates to None. I'm printing it to my HTML output as foo just so I can see what python sees. When I replace this with foo = dtRadios.binSize.data or with foo = dtRadios.dtRadioList.data then whatever option is chosen in that part of the form is printed to screen (and it also works in the context of my app).
But, something about foo = dtRadios.varlist.data is not being evaluated. Does anyone see an obvious error in my code or my thinking?
Grr, solved problem. My dtRadios.varlist was in my HTML, but outside of the form whereas the other parts were properly inside the form. So, the submit button wasn't updating this part of the form.

using another WS as validation Flask/Rest/Mysql

I am trying to build a simple web application with 3 web services. Two of my web services are supposed to validate if a student exist in a course or not. This is done by a simple SELECT-query. My third web service should add a student into a database, but only if the student do exist in the specific course.
This is my validation WS which should return a true/false.
#app.route('/checkStudOnCourse/<string:AppCode>/<string:ideal>', methods= ["GET"])
def checkStudOnCourseWS(AppCode, ideal):
myCursor3 = mydb.cursor()
query3 = ("SELECT studentID FROM Ideal.course WHERE applicationCode = " + "'" + AppCode + "' AND Ideal = " + "'" + ideal + "'")
myCursor3.execute(query3)
myresult3 = myCursor3.fetchall()
if len(myresult3) == 0:
return render_template('Invalid.html')
else:
return jsonify({'Student in course ': True})
Below is regResult which should do a SQL insert into a database. I only want the submit to work if the above result is "True", how can I do that? I know I have not done the INSERT query, but that is not a problem.
What I am unsure about is: How can I only let the submit be be INSERTED if the validation WS is "True".
#app.route('/register', methods=["POST", "GET"])
def regResultat():
if request.method == "POST":
Period = request.form['period']
#ProvNr = request.form['provNr']
Grade = request.form['grade']
Applicationcode = request.form['applicationcode']
#Datum = request.form['datum']
Ideal = request.form['ideal']
CheckStudOnCourse = 'http://127.0.0.1:5000/checkAppCodeWS/'+Applicationcode+'/'+Ideal
CheckStudOnResp = requests.get(CheckStudOnCourse)
At first, such syntax:
if len(myresult3) == 0, can be simplified by if myresult3, because Python evaluates that implicitly to bool.
Secondly, if you once returned from function, there is no need to write an else statement:
if len(myresult3) == 0:
return render_template('Invalid.html') # < -- in case 'True',
# it returns here, otherwise
# function keeps going"""
return jsonify({'Student in course ': True}) # < -- in case 'False', it is returned here
Focusing on your issue, you could do that:
Get your value from ws
CheckStudOnCourse = 'http://127.0.0.1:5000/checkAppCodeWS/'+Applicationcode+'/'+Ideal
CheckStudOnResp = requests.get(CheckStudOnCourse)
Extract json from it:
if result_as_json.status == 200:
result_as_json = CheckStudOnResp.json() # < -- it is now a dict
Do some checks:
if result_as_json.get('Student in course', False): # I highly suggest to use other
# convention to name json keys
# e.g. Student in course ->
# student_exists_in_course
# do your code here

internal server error Flask - Python

This is my code in Python - Flask. Here I am entering data for a Theatre (Theatre table) and then fetching the respective id and then adding the screen to the respective theatre_id in the Screen table.
The problem is Theatre gets added to the database and I am able to fetch the id. The code for Screen doesn't seem to work (for loop does work if I comment out the session.screen add and commit statement)
And even the rollback doesn't happen if screen commit doesn't happen.
session_theatre = Session_theatre()
session_screen = Session_screen()
id = 1
if request.method == "POST":
if form.validate_on_submit():
name = str(form.name.data)
city = str(form.location.data)
address = str(form.address.data)
no_of_screen = int(form.total_no_screen.data)
if (name !="" and name!=" " and city != "" and city != " " and address != ""and address != " " and no_of_screen != None):
t = Theatre(name,city,address,1)
try:
session_theatre.add(t)
session_theatre.commit()
query = session_theatre.query(Theatre).filter_by(name=name,city =city).all()
for i in query :
id = i
for i in range (0,no_of_screen):
flash(id)
screen = Screen(str(i+1),1,20,1,20,id)
session_screen.add(screen)
session_screen.commit()
flash("Successfully added !!")
except :
session_screen.rollback()
session_theatre.rollback()
flash("Oops something went wrong !!")
finally:
session_screen.close()
session_theatre.close()
else :
flash("Please fill the input")
return render_template('admin/add_theatre.html',form = form)
Screen Model
class Screen(db.Model):
__tablename__ = "screens"
id = db.Column(db.Integer,primary_key=True)
screen_num = db.Column(db.String(1))
seat_row_start = db.Column(db.Integer)
seat_row_end = db.Column(db.Integer)
seat_col_start = db.Column(db.Integer)
seat_col_end = db.Column(db.Integer)
theatre_id = db.Column(db.Integer, db.ForeignKey('theatres.id'))
def __init__(self, screen_num,
seat_row_start,seat_row_end,seat_col_start,seat_col_end,theatre_id):
self.screen_num = screen_num
self.seat_row_start = seat_row_start
self.seat_row_end = seat_row_end
self.seat_col_start = seat_col_start
self.seat_col_end = seat_col_end
self.theatre_id = theatre_id
To get a list from the query for session_theatre you have to add all() at the end:
query = session_theatre.query(Theatre).filter_by(name=name,city =city).all()
The query returns a list of Theatre objects and you can access the id attribute of each Theatre object iterating over the list and accessing the attribute by its name:
for obj in query :
for i in range (0,no_of_screen):
flash(obj.id)
screen = Screen(i+1,1,20,1,20,obj.id)
session_screen.add(screen)
session_screen.commit()

Why do I get "Too many indexed properties for entity" error just for 18 items in the list? (Python)

I have a list property
tag_list = db.StringListProperty()
This has been working fine so far, but today when I tried to write a list with 18 items I got the Too many indexed properties for entity: error. I think this is a case of "exploding indexes."
This is my query:
query = Main.all()
query.filter("url =", url)
query.filter("owner =", user)
Reading the documentation my understanding is that this error will be triggered for cases where there are 2000+ items in the list. If this is triggered for 18 items, then, what am I doing wrong and how can I fix this? Thanks.
Update with more code:
query = Main.all()
query.filter("url =", url)
query.filter("owner =", user)
e = query.get()
if e:
e.tag_list = user_tag_list
e.pitch = pitch_original
e.title = title_ascii
e.put()
main_id = e.key().id()
else:
try:
new_item = Main(
url = url,
tag_list = user_tag_list,
pitch = pitch_original,
owner = user,
#title = unicode(title, "utf-8"),
title = title_ascii,
display = True)
#this is where the error occurs in the logs
new_item.put()
And this is the list:
user_tag_list = [u'box', u'jquery', u'working', u'enter', u'initially', u'text', u'showing', u'javascript', u'overflow', u'focus', u'stack', u'field', u'impossible', u'input', u'hidden', u'element', u'toggling', u'toggled']
This is because of exploding indexes.

Categories