I was creating a calculator PyScript program for a school project when the script stopped working as it should. I had to use the alpha PyScript to even make a working calculator for some reason, if that matters.
My code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculators | EZMath</title>
<link rel="icon" type="image/x-icon" href="images/favicon.ico">
<link rel="stylesheet" href="css/pyscript.css" />
<link rel="stylesheet" href="css/styles.css">
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<div class="topbar">
<img class="topbarIcon" src="images/favicon.ico" alt="EZMath">
EZMath
About
Changelog
Calculators
</div>
<div class="header">
<img src="images/header.jpg" alt="Math Homework" class="header">
<div class="header-centered">Calculators</div>
</div>
<div class="basicIntCalc">
<h3>Basic Integer Calculator</h3>
<form onsubmit="return false">
<input type="number" id="basicIntCalc1"/>
<select id="basicIntCalcOperator">
<option value="Add">+</option>
<option value="Subtract">−</option>
<option value="Multiply">×</option>
<option value="Divide">÷</option>
</select>
<input type="number" id="basicIntCalc2"/>
<button id="submit-button" type="submit" pys-onClick="basicIntCalc">Solve</button>
</form>
<p><b>Answer: </b><label id="basicIntCalcOutput">N/A</label></p>
</div>
<div class="basicDecCalc">
<h3>Basic Decimal Calculator</h3>
<form onsubmit="return false">
<input type="number" id="basicDecCalc1"/>
<select id="basicDecCalcOperator">
<option value="Add">+</option>
<option value="Subtract">−</option>
<option value="Multiply">×</option>
<option value="Divide">÷</option>
</select>
<input type="number" id="basicDecCalc2"/>
<button id="submit-button" type="submit" pys-onClick="basicDecCalc">Solve</button>
</form>
<p><b>Answer: </b><label id="basicDecCalcOutput">N/A</label></p>
</div>
<div class="submitCalc">
<h3>Submit a calculator suggestion today!</h3>
<br>
<a class="button" href="https://docs.google.com/forms/d/e/1FAIpQLSeaDHfBJBsTyuQbyaKWdiRkI-h4IkvKwpbCkOTgxc-Cf1YLDA/viewform">Form</a>
<br><br>
</div>
<div class="footer">
<div class="trademark">™ 2023 William Bohrer. All rights reserved.</div>
</div>
<py-script>
from fractions import Fraction
def basicIntCalc(*args, **kwargs):
num1 = int(Element("basicIntCalc1").element.value)
num2 = int(Element("basicIntCalc2").element.value)
operator = Element("basicIntCalcOperator").element.value
if operator == "Add":
output = num1 + num2
pyscript.write("basicIntCalcOutput", output)
elif operator == "Subtract":
output = num1 - num2
pyscript.write("basicIntCalcOutput", output)
elif operator == "Multiply":
output = num1 * num2
pyscript.write("basicIntCalcOutput", output)
else:
output = num1 / num2
pyscript.write("basicIntCalcOutput", output)
def basicDecCalc(*args, **kwargs):
num1 = float(Element("basicDecCalc1").element.value)
num2 = float(Element("basicDecCalc2").element.value)
operator = Element("basicDecCalcOperator").element.value
if operator == "Add":
output = num1 + num2
pyscript.write("basicDecCalcOutput", output)
elif operator == "Subtract":
output = num1 - num2
pyscript.write("basicDecCalcOutput", output)
elif operator == "Multiply":
output = num1 * num2
pyscript.write("basicDecCalcOutput", output)
else:
output = num1 / num2
pyscript.write("basicDecCalcOutput", output)
</py-script>
</body>
</html>
I define 2 functions that make each calculator work (I currently have 2 calculators), and call them each when you press a submit button.
However, the second calculator button doesn't work. The first calculator button makes both of them work. For example, if I put 2.1 and 4.3 into the second calculator and press the second button, it doesn't work. But it does work if I press the first button instead, which should only make the first calculator work.
My apologies if this is a dumb question, I am a beginner with PyScript and Python in general.
Thanks!
IDs are required to be unique. I guess the PyScript transpiler is turning
<button id="buttonid" type="submit" pys-onClick="functioName">Solve</button>
into JavaScript like:
document.getElementById("buttonid").addEventListener("click", functionName);
Since you used the same ID submit-button for both buttons, this is adding both event listeners to the first button with that ID.
Give the buttons different IDs to fix it.
Related
i'm learning Flask/Ajax.
In a POST method i read some data from pwstest.html to run a python script.
Following the Python
#wApp.route("/pwstest",methods=\['GET','POST'\])
def index():
titlepage ='Page title
stato=''
args, data, method = fjrh.handleRequest(request,auth=False)`
if method =='POST':
stato = ''
output = request.get_json()
result = json.loads(output)
logging.info(result)
utente = result\['testoinput'\]
identificativo = result\['numeroinput'\]
dataestrazione = result\['datainput'\]
format='%Y-%m-%d'
dataestrdate = datetime.strptime(dataestrazione,format)
datastr= dataestrdate.strftime("%d-%m-%Y")
parziale= result\['datacheck'\]
if parziale == 'on':`
stringpws = 'http://192.168.x.xxx:5009/plan?diff=True&data=' + datastr
else:
stringpws = 'http://192.168.x.xxx:5009/plan?diff=False&data=01-01-2000'
sqlqry= """select dbo.Callfunction (:1) as result"""
par = (stringpws,)
mApp = MainApp(sql,yyy,mail,walker,parRun, logger)
message= mApp.plan(sqlqry,par)
stato=jsonify(message)
logging.info(stato.status)
return jsonify({"valorestato":message})
else:
return render_template('pwstest.html',nome=titlepage, valorestato=stato)`
And the pwstest.html
<!doctype html>
<html>
<head>
<meta name="description" content="Form di Inserimento di Test">
<meta name="keywords" content="form Inserimento per Test">
<link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='main.css') }}">
</head>
<body>
<dt>
<div>
<form class="'form-signin">
<label for="inputtext" class="sr-only">Addetto</label>
<input type="text" name="inputtext" id="inputtext" class="form-control" placeholder="Nome e Cognome" required autofocus>
</form>
<form>
<label for="inputnumber" class="sr-only">Identificativo</label>
<input type="number" name="inputnumber" id="inputnumber" class="form-control" placeholder="Numero Addetto" required autofocus>
</form>
<form>
<label for="inputrec" class="sr-only">Recalc Date</label>
<input type="date" name="inputdate" id="inputdate" class="form-control" placeholder="Recalc from date" required>
</form>
<form>
<label for="inputflag" class="sr-only">Partial</label>
<input type="checkbox" name="inputflag" id="inputflag" class="form-control" placeholder="Partial" required>
</form>
<form>
<button id="btnSignUp" onclick= 'prelievo();' class="btn btn-lg btn-primary btn-block" type="button">Elabora</button>
</form>
</div>
<div id="finale">
{{valorestato}}
</div>
</dt>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
function prelievo() {
const testoinput = document.getElementById("inputtext").value;
const numeroinput = document.getElementById("inputnumber").value;
const datainput = document.getElementById("inputdate").value;
const datacheck = document.getElementById("inputflag").value;
const dict_values = {testoinput, numeroinput,datainput,datacheck}
const s = JSON.stringify(dict_values);
var workingstatus = 'In Elaborazione'
document.getElementById("finale").innerHTML=workingstatus
console.log(s);
$.ajax({
url:"/pwstest",
type:"POST",
contentType: "application/json",
data: JSON.stringify(s)
})
}
When the script return the results, i need to update the Html page with the result.
Seems the return render_template won't works in the POST method.
Could you help me?
Thank you in advance.
hi I created a simple website to calculate the square of the number. below is the code
calculate.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="homepage.css">
<title>Flask </title>
</head>
<body>
<header>
square
</header>
<div class="congrat">
{{ result }}
</div>
</body>
</html>
homepage.html
<form method="post" action="/square">
<div class="calculate">
<b>Square</b><br/>Num
<input type="text" name="number"><br/>
<input type="submit" value="calculate">
</div>
</form>
python
#app.route("/square", methods=['POST'])
def square():
number = request.form["number"]
return render_template("calculate.html", result = int(number) ** 2)
now I want to display input number in URL path. e.g. http://127.0.0.1:3000/square/10
so I've tried this
<form method="post" action="/square/<number>">
<div class="calculate">
<b>Square</b><br/>Num
<input type="text" name="number"><br/>
<input type="submit" value="calculate">
</div>
</form>
#app.route("/square/<number>", methods=['POST'])
def square(number):
number = request.form["number"]
return render_template("calculate.html", result = int(number) ** 2)
but it didn't work. What could I do?
You could get variables directly parsed from Flask URL
#app.route("/square/<number>", methods=['POST'])
def square(number):
return render_template("calculate.html", result = int(number) ** 2)
Edit:
<form id="your_form" method="post" onsubmit="yourFunction()">
<input type="text" name="keywords">
<input type="text" name="number"><br/>
<input type="submit" value="calculate">
</form>
<script>
function yourFunction(){
var action_src = "/square/" + document.getElementsByName("number")[0].value;
var your_form = document.getElementById('your_form');
your_form.action = action_src ;
}
</script>
I created an app with flask but I'm having a problem with multi-user access bcs of the global variables. Whenever I run the script (it might take minutes) and someone else is trying to access the page and run a script there too a collision appear and data by both users mix.
I truly understand that I should be using OOP in this case, but I'm not able to replicate the OOP usage for this app (yes, I'm an OOP beginner ). Can someone please give me a hint or a little bit of code about OOP for this case?
Much appreciated.
Python:
from flask import Flask, render_template, url_for, request, redirect, Response
from datetime import datetime
import time
import pandas as pd
import re
import os
app = Flask(__name__)
#app.route('/', methods=['POST', 'GET'])
def index():
if request.method == 'POST':
start_date = request.form["Start_date"]
end_date = request.form["End_date"]
dates = pd.period_range(start=start_date, end=end_date, freq='D')
global s_date
global f_date
s_date = dates[0]
f_date = dates[-1]
print(s_date, f_date)
query = request.form["query"].strip()
splitted = query.split("\r\n")
global fiii
fiii = pd.DataFrame()
for x in splitted:
print(x)
for date in dates:
print(date)
directory = '/home/USER/Parquets/{}/{:02d}/{:02d}/'.format(date.year, date.month, date.day)
for filename in os.listdir(directory):
if filename.endswith(".parquet"):
df = pd.read_parquet(directory)
df.set_index("query", inplace=True)
if request.form.get('lowercase') == "on":
df.index = df.index.str.casefold()
if request.form.get('sensitive') == "on":
fiii = fiii.append(df.filter(regex=re.compile(x), axis=0))
else:
fiii = fiii.append(df.filter(regex=re.compile(x, re.IGNORECASE), axis=0))
fiii = fiii.groupby(['query'])["total"].sum().sort_values(ascending=False)
if request.form.get('csv') == "on":
return redirect("/getCSV")
else:
pass
# return render_template("index.html")
return fiii.to_frame().to_html(table_id="table")
else:
return render_template("index.html")
#app.route("/getCSV")
def getPlotCSV():
return Response(
fiii.to_csv(encoding="UTF-8", sep="\t", header=True),
mimetype="text/csv",
headers={"Content-disposition":
f"attachment; filename={s_date}-{f_date}.csv"})
if __name__ == "__main__":
app.run(debug=True,port=4444)
HTML:
<html lang="en"><head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mate rialize/1.0.0/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js /materialize.min.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel ="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
<form class="col s6 offset-s3" action="/" method="POST">
<div class="valign-wrapper col s12">
<h3 class="col s6">Query master</h3>
<div class="right-align input-field col s6">
<button class="btn btn-large btn-floating waves- effect waves-light" type="submit" name="action">
<i class="material-icons right">send</i>
</button>
</div>
</div>
<div class="input-field col s12">
<input type="text" id="date-start" class="datepicker " name="Start_date">
<label for="date-start">Start Date</label>
</div>
<div class="input-field col s12">
<input type="text" id="date-end" class="datepicker" name="End_date">
<label for="date-end">End Date</label>
</div>
<label class="input-field col s12">
<input type="checkbox" name="lowercase" />
<span>Lowercase queries</span>
</label>
<label class="input-field col s12">
<input type="checkbox" name="sensitive" />
<span>Case sensitive</span>
</label>
<label class="input-field col s12">
<input type="checkbox" name="csv" />
<span>CSV export (Funkční pouze csv export)</span>
</label>
<div class="input-field col s12">
<textarea id="textarea1" name="query" class="materia lize-textarea"></textarea>
<label for="textarea1">Queries (RegEx supported)</la bel>
</div>
</form>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.datepicker');
var instances = M.Datepicker.init(elems, {
format: 'm/d/yyyy',
});
});
</script>
</div>
</body>
</html>
Your problem has absolutely nothing to do with OO - it's only the result of using gobal variables.
Your flask server process will serve all incoming requests, one after the other. So what happens in a multi-user scenario is:
1/ user A posts to index. This assigns values to your globals s_date, f_date and fills.
2/ user A is redirected to getCSV
3/ in the meantime, user B posts to index. This rebinds your globals s_date, f_date and fills to new values
4/ user A's browser has followed the redirection, and renders the fill of user B.
The solution is quite simple: do NOT use global state for per-user data persistance - you want either a user session for short-lived session data and/or a RDBMS for long-lived user data.
i'm creating a python web application which get multiple user input from input type="number" and calculation will be done when input type="submit" is pressed. I managed to do it but it appears that input that user entered earlier disappear because the page refresh when submitted. Can anyone help me how to keep the user input even after input type="submit" is pressed.
This is my python script:
from flask import Flask, render_template, request
import math
app = Flask(__name__, template_folder='C:\\Users\\iyzadsyammil\\.PyCharmCE2017.1\\config\\fileTemplates')
#app.route('/')
def index():
return render_template('index.html')
#app.route('/Menu')
def showmenu():
return render_template('index.html')
#app.route('/App',methods=['GET', 'POST'])
def showapp():
outpb=0
x=0
logpb=0
error=" "
if request.method=='POST':
ingor = request.form['inGOR']
inog = request.form['inOG']
ingg = request.form['inGG']
inws = request.form['inWS']
intemp = request.form['inT']
inpress = request.form['inP']
innc = request.form['inNC']
cor1 = request.form['cor1']
cor2 = request.form['cor2']
cor3 = request.form['cor3']
cor4 = request.form['cor4']
ingor = float(ingor)
inog = float(inog)
ingg = float(ingg)
inws = float(inws)
intemp = float(intemp)
inpress = float(inpress)
innc = float(innc)
try:
if cor1 == "VB":
if inog <= 30:
outpb = ((27.64*ingor/ingg)*10**((-11.172*inog)/(intemp+460)))**(1/1.0937)
else:
outpb = ((56.06*ingor/ingg)*10**((-10.393*inog)/(intemp+460)))**(1/1.187)
elif cor1 == "AM":
outpb = 0.00538088*ingor**0.715082*ingg**-1.87784*(141.5/(inog+131.5))**3.1437*(intemp+460)**1.32657
elif cor1 == "G":
x = (ingor/ingg)**0.816*((intemp**0.172)/(inog**0.989))
logpb = 1.7669 + 1.7447 * math.log10(x) - (0.30218*(math.log10(x)**2))
outpb = 10**logpb
elif cor1 == "PF":
x = 7.916*(10**-4)*inog**1.541-(4.561*(10**-5)*intemp**1.3911)
outpb = ((112.727*ingor**0.577421)/(ingg**0.8439*10**x))-1391.051
elif cor1 == "S":
outpb = 18.2*((ingor/ingg)**0.83*10**(0.00091*intemp-0.0125*inog)-1.4)
else:
outpb = "Invalid Correlation!!"
except ValueError:
error = "Please enter an appropriate value!"
return render_template('app.html',error=error,outpb=outpb)
if __name__ == "__main__":
app.run(debug=True)
This is my current html page :
<!DOCTYPE html>
<html lang="en">
<head>
<title>Testing Program</title>
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="header">
<nav>
<ul class="nav nav-pills pull-right">
<li role="presentation" class="active">Home
</li>
<li role="presentation" class="active">App
</li>
<li role="presentation" class="active">Log In
</li>
<li role="presentation" class="active">Sign Up
</li>
</ul>
</nav>
<h3 class="text-muted">Experiment</h3>
</div>
<div class="jumbotron">
<h1>WELCOME!!</h1>
</div>
<div class="row marketing">
<form method="POST" class="col-lg-6" >
<h3>PVT Application</h3>
<br>
<table>
<tr><td>Input Data</td><td></td><td></td></tr>
<tr><td>Solution GOR(Rs) </td><td><input type="number" step="any" name="inGOR"></td><td>scf/bbl</td></tr>
<tr><td>Oil Gravity </td><td><input type="number" step="any" name="inOG"></td><td>API</td></tr>
<tr><td>Gas Gravity </td><td><input type="number" step="any" name="inGG"></td><td>gr/cc</td></tr>
<tr><td>Water Salinity </td><td><input type="number" step="any" name="inWS"></td><td>ppm</td></tr>
<tr><td>Temperature </td><td><input type="number" step="any" name="inT"></td><td>◦F</td></tr>
<tr><td>Pressure </td><td><input type="number" step="any" name="inP"></td><td>Psia</td></tr>
<tr><td>Nitrogen Content </td><td><input type="number" step="any" name="inNC"></td><td>%mol</td></tr>
</table>
<br>
<table>
<tr><td>Correlation</td><td></td></tr>
<tr>
<td>Bubble Point Pressure(Pb) </td>
<td>
<select name="cor1">
<option value="none"></option>
<option value="VB">Vasquez and beggs</option>
<option value="AM">Al-Marhoun</option>
<option value="G">Glaso</option>
<option value="PF">Petrosky and Farshad</option>
<option value="S">Standing</option>
</select>
</td>
</tr>
<tr>
<td>Solution GOR(Rs)</td>
<td>
<select name="cor2">
<option value=" "></option>
<option value="VB">Vasquez and beggs</option>
<option value="AM">Al-Marhoun</option>
<option value="G">Glaso</option>
<option value="PF">Petrosky and Farshad</option>
<option value="S">Standing</option>
</select>
</td>
</tr>
<tr>
<td>Oil Formation Volume Factor(Bo) </td>
<td>
<select name="cor3">
<option value=" "></option>
<option value="VB">Vasquez and beggs</option>
<option value="AM">Al-Marhoun</option>
<option value="G">Glaso</option>
<option value="PF">Petrosky and Farshad</option>
<option value="S">Standing</option>
</select>
</td>
</tr>
<tr>
<td>Viscosity(µo) </td>
<td>
<select name="cor4">
<option value=" "></option>
<option value="CC">Chew Connally</option>
<option value="BR">Beggs Robinson</option>
</select>
</td>
<td><input type="submit" value="Calculate"></td>
</tr>
</table>
<br>
<table >
<tr><td>Result</td><td></td></tr>
<tr><td>Pb</td><td>{{outpb}}</td></tr>
<tr><td>Rs(Solution GOR)</td><td></td></tr>
<tr><td>Corrected Pb(Nitrogen Effect)</td><td></td></tr>
<tr><td>Bo</td><td></td></tr>
<tr><td>Co</td><td></td></tr>
<tr><td>µo</td><td></td></tr>
</table>
<!--
<table>
<tr><td>Enter Length (cm) : {{l}}</td><td><input type="number" step="any" name="l"></td></tr>
<tr><td>Enter Width (cm) : {{w}}</td><td><input type="number" step="any" name="w"></td></tr>
<tr><td>Enter Height (cm) : {{h}}</td><td><input type="number" step="any" name="h"></td></tr>
<tr><td><input type="submit" value="Calculate"></td></tr>
</table>
<br/>
</form>
</div>
<footer class="footer">
<p>Copyright © Invigour Energy 2016</p>
</footer>
</div>
</body>
</html>
No jQuery, no Ajax. but obviously you need some JS.
<input id="number" type="number" value="num">
<input id="submit" type="submit" value="submit">
document.getElementById("submit").addEventListener("click", function(){
var val = document.getElementById("number").value
sessionStorage.setItem("number", val);
});
window.onload = function() {
var session_value = sessionStorage.getItem("number") || 0;
document.getElementById("number").value = session_value;
}
If you give some clues that how do you use python (db interaction, templating etc.) another solutions might be considered.
sessionStorage
The <input type="submit"> will reach the action attribute of your <form> when clicked, or will refresh the page if the action is empty.
You can use a <button> element and assign it a function on the click event, for example:
<!-- There is no form needed if you don't need to submit -->
<div id="form">
<input type="number" id="myNumber">
<input type="number" id="myOtherNumber">
<button type="button" id="submit">Calculation</button>
</div>
JS part:
window.onload = function () {
/* get elements */
var num_1 = document.getElementById('myNumber'),
num_2 = document.getElementById('myOtherNumber'),
btn = document.getElementById('submit');
/* do what you want with your number
when the button is clicked */
btn.onclick = function () {
window.console.log(num_1.value + num_2.value);
};
};
So I've been looking at this for over an hour and I cannot figure out what the heck is going on.
The script is printing only a ">"
It's suppose to print the full HTML and then, after the form is submitted, print "print_after"
import webapp2
class MainHandler(webapp2.RequestHandler):
def get(self):
p = Page()
if self.request.GET:
name = self.request.GET['name']
age = self.request.GET['age']
time = self.request.GET['time']
model = self.request.GET['model']
radio = self.request.GET['trade']
self.response.write(p.print_after(name, age, time, model, radio))
print name + age + time + model + radio
else:
self.response.write(p.print_one)
class Page(object):
def __init__(self):
self.page_body = '''
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/main.css">
<title>Audi Test Drive Request</title>
</head>
<body>
<img src="assets/custom/images/logo.png" title="logo" alt="" width="200px" height="150px"/>
<h3>It's awesome that you want to test-drive one of our vehicles</h3>
<form method="GET" action="">
<label>Name</label>
<br>
<input type="text" name="name" required>
<br>
<label>Age</label>
<br>
<input type="text" name="age" required>
<br>
<label>Time</label>
<br>
<select name="time" required>
<option value="12:00 PM">12:00 PM</option>
<option value="12:30 PM">12:30 PM</option>
<option value="1:00 PM">1:00 PM</option>
</select>
<br>
<label>Model</label>
<br>
<select name="model" required>
<option value="2008 Audi A4">2008 Audi A4</option>
<option value="2008 Audi S4">2008 Audi S4</option>
<option value="2008 Audi RS4">2008 Audi RS4</option>
</select>
<br>
<label>Are you trading in a vehicle?</label>
<br>
<input type="radio" name="trade" value="yes" required>Yes<br>
<input type="radio" name="trade" value="no" required>No<br>
<br>
<input type="submit" value="Request Test Drive">
</form>
</body>
</html>
'''
self.page_after = '''
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/main.css">
<title>Audi Test Drive Request</title>
</head>
<body>
<img src="assets/custom/images/logo.png" title="logo" alt="" width="200px" height="150px"/>
<h3>It's awesome that you want to test-drive one of our vehicles</h3>
</body
</html>
'''
def print_one(self):
page_content = self.page_body
page_content = page_content.format(**locals())
return page_content
def print_after(self, name, age, time, model, radio):
after_page_content = self.page_after
after_page_content = after_page_content.format(**locals())
return after_page_content
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)
I tested your code and rearranged it a little. I used http post for submitting the form and then it prints the form variables.
import webapp2
class HelloWebapp2(webapp2.RequestHandler):
def get(self):
self.response.write('''<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/main.css">
<title>Audi Test Drive Request</title>
</head>
<body>
<img src="assets/custom/images/logo.png" title="logo" alt="" width="200px" height="150px"/>
<h3>It's awesome that you want to test-drive one of our vehicles</h3>
<form method="POST" action="">
<label>Name</label>
<br>
<input type="text" name="name" required>
<br>
<label>Age</label>
<br>
<input type="text" name="age" required>
<br>
<label>Time</label>
<br>
<select name="time" required>
<option value="12:00 PM">12:00 PM</option>
<option value="12:30 PM">12:30 PM</option>
<option value="1:00 PM">1:00 PM</option>
</select>
<br>
<label>Model</label>
<br>
<select name="model" required>
<option value="2008 Audi A4">2008 Audi A4</option>
<option value="2008 Audi S4">2008 Audi S4</option>
<option value="2008 Audi RS4">2008 Audi RS4</option>
</select>
<br>
<label>Are you trading in a vehicle?</label>
<br>
<input type="radio" name="trade" value="yes" required>Yes<br>
<input type="radio" name="trade" value="no" required>No<br>
<br>
<input type="submit" value="Request Test Drive">
</form>
</body>
</html>
''')
def post(self):
if self.request.POST:
name = self.request.POST['name']
age = self.request.POST['age']
time = self.request.POST['time']
model = self.request.POST['model']
radio = self.request.POST['trade']
self.response.write(name +" " + age +" " + time +" " + model +" " + radio)
app = webapp2.WSGIApplication([
('/', HelloWebapp2),
], debug=True)
def main():
from paste import httpserver
httpserver.serve(app, host='127.0.0.1', port='8080')
if __name__ == '__main__':
main()
The above code starts a local webserver at port 8080. It might not do exactly what you want, but much is there. You can also run it in appengine.