Get the value from flask html to python - python

Given below the html code I have created flask server using python. Here I'm
taking only checkboxSelectCombo and after selecting the checkboxes in the flask UI, I want to print those values in python as I click on any flask button.
How to get and print that values in the python?
If anyone knows the answer please help me out.
Thank you
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>OPTIMIZATION</title>
<title></title>
<!-- Ignite UI Required Combined CSS Files -->
<link href="http://cdn-na.infragistics.com/igniteui/2018.1/latest/css/themes/infragistics/infragistics.theme.css" rel="stylesheet" />
<link href="http://cdn-na.infragistics.com/igniteui/2018.1/latest/css/structure/infragistics.css" rel="stylesheet" />
<script src="http://ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.8.3.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<!-- Ignite UI Required Combined JavaScript Files -->
<script src="http://cdn-na.infragistics.com/igniteui/2018.1/latest/js/infragistics.core.js"></script>
<script src="http://cdn-na.infragistics.com/igniteui/2018.1/latest/js/infragistics.lob.js"></script>
</head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
background-color: #dddddd;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 1px;
}
</style>
<body bgcolor="#a9d284">
<img src="/static/images/logo.gif" alt="Related Book 1" width="300" height="80" align="right">
<script src="/static/scripts.js" charset="utf-8"></script>
<h1>PORTFOLIO OPTIMIZATION</h1>
<style>
.combo-label {margin-bottom:.5em;}
</style>
<form method="POST" action="">
<h4 class="combo-label">SELECT THE STOCK OPTIONS</h4>
<div id="checkboxSelectCombo"></div>
<br><br>
<h4>SELECT THE INPUT DATE</h4>
<input type="date" name="date1" placeholder="Start date">
<input type="date" name="date2" placeholder="End date">
<br><br>
<h4>ENTER CONSTRAINTS CRITERIA</h4>
<table>
<tr>
<th> </th>
<th>Cheap</th>
<th>Moderate</th>
<th>Expensive</th>
<th>PUT</th>
<th>CALL</th>
<th>Not Recommended</th>
<th>Highly Liquid</th>
<th>Moderately Liquid</th>
<th>Less Liquid</th>
<th>MPO</th>
<th>PO</th>
<th>LPO</th>
</tr>
<tr>
<td>Group_Min</td>
<td class="td"><input type="text" name="min1"/></td>
<td class="td"><input type="text" name="min2" /></td>
<td class="td"><input type="text" name="min3"/></td>
<td class="td"><input type="text" name="min4"/></td>
<td class="td"><input type="text" name="min5"/></td>
<td class="td"><input type="text" name="min6"/></td>
<td class="td"><input type="text" name="min7"/></td>
<td class="td"><input type="text" name="min8"/></td>
<td class="td"><input type="text" name="min9"/></td>
<td class="td"><input type="text" name="min10"/></td>
<td class="td"><input type="text" name="min11"/></td>
<td class="td"><input type="text" name="min12"/></td>
</tr>
<tr>
<td>Group_Max</td>
<td class="td"><input type="text" name="max1"/></td>
<td class="td"><input type="text" name="max2"/></td>
<td class="td"><input type="text" name="max3"/></td>
<td class="td"><input type="text" name="max4"/></td>
<td class="td"><input type="text" name="max5"/></td>
<td class="td"><input type="text" name="max6"/></td>
<td class="td"><input type="text" name="max7"/></td>
<td class="td"><input type="text" name="max8"/></td>
<td class="td"><input type="text" name="max9"/></td>
<td class="td"><input type="text" name="max10"/></td>
<td class="td"><input type="text" name="max11"/></td>
<td class="td"><input type="text" name="max12"/></td>
</tr>
</table>
<br><br>
<input type="submit" value="GET RESULTS">
</form>
<script>
var colors = [
{ Name: "FP FP Equity" },
{ Name: "SAN FP Equity" },
{ Name: "NOK1V FH Equity" },
{ Name: "SAN SQ Equity" },
{ Name: "EOA GY Equity" },
{ Name: "SIE GY Equity" },
{ Name: "ENI IM Equity" },
{ Name: "UC IM Equity" },
{ Name: "INGA NA Equity" },
{ Name: "TEF SQ Equity" },
{ Name: "BNP FP Equity" },
{ Name: "BBVA SQ Equity" },
{ Name: "ALV GY Equity" }
];
$(function () {
$("#singleSelectCombo").igCombo({
width: 300,
dataSource: colors,
textKey: "Name",
valueKey: "Name",
dropDownOnFocus: true,
dropDownOrientation: "bottom"
});
$("#multiSelectCombo").igCombo({
width: 300,
dataSource: colors,
textKey: "Name",
valueKey: "Name",
multiSelection: {
enabled: true
},
dropDownOrientation: "bottom"
});
$("#checkboxSelectCombo").igCombo({
width: 300,
dataSource: colors,
textKey: "Name",
valueKey: "Name",
multiSelection: {
enabled: true,
showCheckboxes: true
},
dropDownOrientation: "bottom"
});
});
</script>
</body>
</html>
<!doctype html>
<title>Simple tables</title>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
<div class=page>
<h2>OPTIMIZED VALUES</h2>
{% for table in tables %}
<h3>{{titles[loop.index]}}</h3>
{{ table|safe }}
{% endfor %}
</div>
Python backend code
from flask import Flask, render_template, request
from optimization_excel.app import rough_bkend as r1
app = Flask(__name__)
#app.route('/opt')
def index():
return render_template('rough_portopt.html')
#app.route('/opt', methods=['POST'])
def opt():
val = request.form.getlist('checkboxSelectCombo')
print(val)
res1, res2, res3 = r1.get_res1()
return render_template('rough_portopt.html', tables=[res1.to_html(), res2.to_html()],
titles=['na', 'Test Results', 'Constraint values'])
if __name__ == "__main__":
app.run(debug=True)

So I place import pdb; pdb.set_trace() right before your print(val) code and found
-> print(val)
(Pdb) p request.form
ImmutableMultiDict([('date1', ''), ('date2', ''), ('min1', ''), ('min2', ''),
('min3', ''), ('min4', ''), ('min5', ''), ('min6', ''), ('min7', ''), ('min8', ''),
('min9', ''), ('min10', ''), ('min11', ''), ('min12', ''), ('max1', ''), ('max2', ''),
('max3', ''), ('max4', ''), ('max5', ''),('max6', ''), ('max7', ''), ('max8', ''),
('max9', ''), ('max10', ''), ('max11', ''), ('max12', '')])
So we see checkboxSelectCombo is not part of the form. Right-clicking on the drop box and select Inspect, I examine the generated HTML and find
<input type="hidden" class="ui-igcombo-hidden-field" value="SAN FP Equity">
Ah, this element doesn't have a name. Your problem seems to be in your javascript, not flask.

Related

Missing columns in final html table after rendering the pandas dataframe to html

I am writing the below df values into a html template. I am missing chemistry and algebra column in the final output html table.
import pandas as pd
df = pd.DataFrame({'name': ['Somu', 'Kiku', 'Amol', 'Lini'],
'physics': [68, 74, 77, 78],
'chemistry': [84, 56, 73, 69],
'algebra': [78, 88, 82, 87]})
df_html = df.to_html()
template_vars = { "html_table":df_html}
f = open(output.html, 'w', encoding='utf-8')
html_template ="metrics.html"
temp = Template(open(html_template, 'r').read())
template = temp.render(template_vars)
f.write(template)
f.close()
In the below Metrics.html has 4 buttons, out of which 2nd button is not showing up all the columns.
Metrics.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style>
#incorrect-response-panel .panel{
border-radius: 0;
}
.response-panel-title {
font-weight: normal;
}
.doc-info h3 {
font-weight: normal;
}
</style>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.collapsible {
background-color: #777;
color: white;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
}
.active, .collapsible:hover {
background-color: #555;
}
.collapsible:after {
content: '\002B';
color: white;
font-weight: bold;
float: right;
margin-left: 5px;
}
.active:after {
content: "\2212";
}
.content {
padding: 0 18px;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
background-color: #f1f1f1;
}
</style>
</head>
<body>
<button id=button1 type="button" class="collapsible">Top 1 Correct answer </button>
<div class="content">
{{correct_tab1}}
</div>
<div>
</br> </br>
</div>
<button id=button2 type="button" class="collapsible">Top 1 Incorrect answer </button>
<div class="content">
{{html_table}}
</div>
<div>
</br> </br>
</div>
<button id=button3 type="button" class="collapsible">Top 1 Correct answer </button>
<div class="content">
{{correct_tab1}}
</div>
<div>
</br> </br>
</div>
<button id=button4 type="button" class="collapsible">Top 1 Incorrect answer </button>
<div class="content">
{{incorrect_tab1}}
</div>
<div>
</br> </br>
</div>
https://codepen.io/code_rev/pen/VwKBpRY
As I testing your code partly after romoving () in (df=) and (`df_html=) in your qustion:
import pandas as pd
df = pd.DataFrame({'name': ['Somu', 'Kiku', 'Amol', 'Lini'],
'physics': [68, 74, 77, 78],
'chemistry': [84, 56, 73, 69],
'algebra': [78, 88, 82, 87]})
df_html = df.to_html()
we find the content of df_html is (just reformating):
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>name</th>
<th>physics</th>
<th>chemistry</th>
<th>algebra</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>Somu</td>
<td>68</td>
<td>84</td>
<td>78</td>
</tr>
<tr>
<th>1</th>
<td>Kiku</td>
<td>74</td>
<td>56</td>
<td>88</td>
</tr>
<tr>
<th>2</th>
<td>Amol</td>
<td>77</td>
<td>73</td>
<td>82</td>
</tr>
<tr>
<th>3</th>
<td>Lini</td>
<td>78</td>
<td>69</td>
<td>87</td>
</tr>
</tbody>
</table>
so we find the complete DataFrame with all the columns.
Hence, this part of the code is correct (after removing the character (`) I mentioned above).
The only suspicious sentence, in my thought, is
template = temp.render(template_vars)
which depneds on html_template ="metrics.html" and template_vars = { "html_table":df_html}
Therefore, if there is a problem still existed, it would be necessary to add 'metrics.html`. we may find something.
Extending
In the 'metrics.html` you uploaded, I have changed the following part:
<button id=correct1 type="button" class="collapsible">Correct answer </button>
<div class="content">
{{correct_tab1}}
</div>
<div>
</br> </br>
</div>
<button id=incorrect1 type="button"
to
<button id=correct1 type="button" class="collapsible">Correct answer </button>
<div class="content">
{{html_table}} <!-- to match your question -->
</div>
<div>
</br> </br>
</div>
then after running your code, the rendered part in output.html related to the table we intend is:
<button id=incorrect1 type="button" class="collapsible"> Incorrect answer </button>
<div class="content">
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>name</th>
<th>physics</th>
<th>chemistry</th>
<th>algebra</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>Somu</td>
<td>68</td>
<td>84</td>
<td>78</td>
</tr>
<tr>
<th>1</th>
<td>Kiku</td>
<td>74</td>
<td>56</td>
<td>88</td>
</tr>
<tr>
<th>2</th>
<td>Amol</td>
<td>77</td>
<td>73</td>
<td>82</td>
</tr>
<tr>
<th>3</th>
<td>Lini</td>
<td>78</td>
<td>69</td>
<td>87</td>
</tr>
</tbody>
</table>
</div>
<div>
</br> </br>
</div>
so we notice that {{html_table}} we replaced correctly with HTML code of the table including all the columns.
so I do not find any problem.
I guess, you may investigate an old version of output.html and the generated one is in another folder.
or as it is clear, you did not upload the 'metrics.html` you work with, since the uploaded one does not contain the HTML you added in your question

Updating the same site with Python's Flask module

Background:
I'm fairly new to developing front end and the Flask module in Python. I am difficulty updating the same page.
What I want to achieve:
There are three parts to what I want to achieve
Part/Step 1: I can create a form such as the one below
Part/Step 2: When the form is filled in as below, and the [verify] button is hit it goes to Step 3
Part/Step 3: Once the verify button is hit, just underneath it the information that was passed gets placed underneath it. There are also two buttons, with [commit] and [cancel] button. If [cancel] is hit, the site resets to as it were in Step 1. If [commit] is hit, it goes to a different website in step 4
Part/Step 4: If [commit] is hit from the image above, another site is retrieved with the following message.
Note:
Happy to share my code, but I just have the empty form in step 1. I can't proceed after that. As mentioned, I'm very new to front end stuff.
Update:
I'm having difficulties with 2 things currently:
When I click [cancel], the whole form shifts to the left (How can I make it centered?)
How can I print multiple things (ideally in a centered table) after hitting the [verify] button
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
document.getElementById("verify").style.display = "none";
document.getElementById("committed").style.display = "none";
})
function onVerify() {
document.getElementById("verifyName").innerHTML = 'First Name: ' + document.getElementById("first_name").value
document.getElementById("verify").style.display = "block";
}
function onCommit() {
document.getElementById("form").style.display = "none";
document.getElementById("verify").style.display = "none";
document.getElementById("committed").style.display = "block";
}
function onCancel() {
document.getElementById("form").style.display = "block";
document.getElementById("verify").style.display = "none";
document.getElementById("name").value = ""
}
</script>
<style>
h3 {text-align: center;}
.right {
text-align: right;
margin-right: 1em;
}
.center {
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<h3>Personnel Details</h3>
<div class="center" id="form">
<table>
<tr>
<td class="right">
<label>Salutation:</label>
</td>
<td>
<select name="gender">
<option value=""></option>
<option value="male">Mr.</option>
<option value="female">Ms.</option>
</select>
</td>
</tr>
<tr>
<td class="right">
<label>First Name:</label>
</td>
<td>
<input id="first_name">
</td>
</tr>
<tr>
<td class="right">
<label>Middle Name:</label>
</td>
<td>
<input id="middle_name">
</td>
</tr>
<tr>
<td class="right">
<label>Last Name:</label>
</td>
<td>
<input id="last_name">
</td>
</tr>
<tr>
<td class="right">
<label>Email:</label>
</td>
<td>
<input id="email">
</td>
</tr> <tr>
<td class="right">
<label>DOB:</label>
</td>
<td>
<input type="date" name="issue_date" value="" min="1900-01-01" max="2100-12-31">
</td>
</tr>
<tr>
<td>
</td>
<td class="center">
<div>
<button onclick="onVerify()">Verify</button>
</div>
</td>
</tr>
</table>
</div>
<div id="verify">
<div id="verifyName">
</div>
<button onclick="onCommit()">Commit</button>
<button onclick="onCancel()">Cancel</button>
</div>
<div id="committed">
Committed! :)
</div>
</html>
This is just the minimal code, I have used to just give an idea, how to achieve the similar behavior, with just one input field. You can easily extend this with other fields.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
document.getElementById("verify").style.display = "none";
document.getElementById("committed").style.display = "none";
})
function onVerify() {
document.getElementById("verifyName").innerHTML = 'First Name: ' + document.getElementById("name").value
document.getElementById("verify").style.display = "block";
}
function onCommit() {
document.getElementById("form").style.display = "none";
document.getElementById("verify").style.display = "none";
document.getElementById("committed").style.display = "block";
}
function onCancel() {
document.getElementById("form").style.display = "block";
document.getElementById("verify").style.display = "none";
document.getElementById("name").value = ""
}
</script>
<div id="form">
<label> First Name:
<input id="name">
</label>
<div>
<button onclick="onVerify()">Veryfy</button>
</div>
</div>
<div id="verify">
<div id="verifyName">
</div>
<button onclick="onCommit()">Commit</button>
<button onclick="onCancel()">Cancel</button>
</div>
<div id="committed">
Committed! :)
</div>

Python Requests, Successful website log in but redirects me to log in page

I am trying to scrape a website using Python's Requests Module
It's a website we can only access inside our company.
Every time I try to scrape the website using get(), it show's this
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>401 Authorization Required</title>
</head><body>
<h1>Authorization Required</h1>
<p>This server could not verify that you
are authorized to access the document
requested. Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.</p>
<hr>
<address>Apache/2.2.13 (Red Hat) Server at tcfabcert Port 80</address>
</body></html>
But when I insert the auth=('user','pass'), it get's a respone of 200 but it doesn't log me in and every time I try to log in using post() method it just keeps redirecting me to the same Login Page.
Here is my code:
import requests
payload = {'userID': 'user',
'password': 'mypass',
'userLocale': 'US CA',
'userBU': 'MB',
'servName': 'Certification',
'login': 'Login',
'rememberFlag': 'false',
'hiddenHost': 'cpc44743'}
cookie = {'Cookie': 'JSESSIONID=AF1A7CC747492C3D4259B230A5F7635A.PKYCUbG8Dba7VqoxAzD4WA'}
header = {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding':'gzip, deflate',
'Accept-Language':'en-US,en;q=0.9',
'Cache-Control':'max-age=0',
'Connection':'keep-alive',
'Content-Length':'138',
'Content-Type':'application/x-www-form-urlencoded',
'Cookie':'JSESSIONID=AF1A7CC747492C3D4259B230A5F7635A.PKYCUbG8Dba7VqoxAzD4WA',
'Host':'tcfabcert',
'Origin':'http://tcfabcert',
'Referer':'http://tcfabcert/ws/ess/default.jsp',
'Upgrade-Insecure-Requests':'1',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'}
with requests.Session() as r:
url = "http://tcfabcert/ws/ess/"
res = r.get(url, auth=('user', 'password')).text
res2 = r.post(url, auth=('user', 'password'), datas=payload, headers=header, allow_redirects=True)
Here is the code of the log in page
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta name="GENERATOR"
content="IBM WebSphere Page Designer V3.5.2 for Windows" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<title>Editorial System</title>
<link rel="stylesheet" type="text/css" href="/ws/ess/theme/Style2.css" />
<script type="text/javascript">
var GB_ROOT_DIR = "/ws/ess/greybox/";
</script>
<script type="text/javascript" src="/ws/ess/greybox/AJS.js"></script>
<script type="text/javascript" src="/ws/ess/greybox/AJS_fx.js"></script>
<script type="text/javascript" src="/ws/ess/greybox/gb_scripts.js"></script>
<link href="/ws/ess/greybox/gb_styles.css" rel="stylesheet" type="text/css" media="all" />
<script language="JavaScript1.2">
<!-- Hide from older browsers
// Original JavaScript code by Duncan Crombie: dcrombie at chirp.com.au
// Please acknowledge use of this code by including this header.
function getCookie(name) { // use: getCookie("name");
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
var today = new Date();
var expiry = new Date(today.getTime() + 28 * 24 * 60 * 60 * 1000); // plus 28 days
function setCookie(name, value) { // use: setCookie("name", value);
document.cookie=name + "=" + escape(value) + "; expires=" + expiry.toGMTString();
}
// Stop hiding -->
function dispHandle(obj) {
if (obj.style.display == "none")
obj.style.display = "";
else
obj.style.display = "none";
}
</script>
<script language="JavaScript1.2">
function rememberMe(cbox)
{
userIDValue = document.forms(0).userID.value;
userPWDValue = document.forms(0).password.value;
userLocale = document.forms(0).userLocale.value;
userBU = document.forms(0).userBU.value;
if (cbox.checked)
{
document.forms(0).rememberFlag.value = "true";
setCookie("userID", userIDValue);
setCookie("userPWD", userPWDValue);
setCookie("userLocale", userLocale);
setCookie("userBU", userBU);
}
}
//function to reset the locale/bu
function setUserLocale(userLocale, userBU)
{
setCookie("userBU", userBU);
setCookie("userLocale", userLocale);
document.forms(0).submit();
}
function submitForm() {
userIDValue = new String();
userIDValue = document.forms(0).userID.value;
userPWDValue = document.forms(0).password.value;
userLocale = document.forms(0).userLocale.value;
userBU = document.forms(0).userBU.value;
rFlag = document.forms(0).rememberFlag.value;
if (document.forms(0).password.value.length <1)
{
//alert("Please enter password");
//alert("Please enter password");
}
else if (rFlag = "true")
{
setCookie("userID", userIDValue);
setCookie("userPWD", userPWDValue);
setCookie("userLocale", userLocale);
setCookie("userBU", userBU);
}
document.forms(0).submit();
}
function _HpbJumpURL(url)
{
if (url != '')
{
window.location = url;
}
}
function checkBrowser(){
var userID=getCookie("userID");
var userPWD = getCookie("userPWD");
var userLocale = getCookie("userLocale");
var userBU = getCookie("userBU");
if (userID != null && userPWD != null)
{
document.forms(0).userID.value = userID;
document.forms(0).password.value = userPWD;
}
this.ver=navigator.appVersion
this.dom=document.getElementById?1:0
//Changes made by ANANDA5 for IE8 Migration
//this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom)?1:0;
this.ie8=(this.ver.indexOf("MSIE 8")>-1 && this.dom)?1:0;
//End
var hName= window.location.host;
var hPlatform = "";
if (hName.indexOf("cert") != -1 )
{
hPlatform = "Certification";
}
else if (hName.indexOf("prod") != -1)
{
hPlatform = "Production";
}
else if (hName.indexOf("int") != -1)
{
hPlatform = "Development";
}
else if (hName.indexOf("lngcentral") != -1)
{
hPlatform = "Production";
}
else
{
hPlatform = "Development";
}
document.login.servName.value=hPlatform;
return this
}
function addToFavorites()
{
window.external.AddFavorite(window.url, "EdSched");
}
function showNew()
{
var userBU = getCookie("userBU");
if (userBU != null && userBU != "LNFR")
{
var newPage=getCookie("newPage3-17");
if (newPage == null || newPage=="TRUE")
{
whatsNew =GB_showFullScreen("What's new for this Release","../whatsnew.jsp");
}
}
}
</script>
</head>
<body onload="checkBrowser(); showNew();">
<form name="login" method="post" action="/ws/ess/default.jsp"><!-- Set the Default Locale -->
<br>
<br>
<br>
<center>
<table style='background: #dae0d2 url("images/bg.gif") repeat-x bottom; border: 1px thin'>
<tbody>
<tr>
<td align="center"><img src="/ws/ess/images/edsched.png" border="0"></td>
</tr>
<tr>
<td align="center"><label class="TextLabel4">(Editorial Scheduling System)</label> <br>
<br>
</td>
</tr>
<tr>
<td align="center"><label class="TextLabel4">Enter the Login Details</label> <br>
</td>
</tr>
</tbody>
</table>
</center>
<center>
<table style='background: #dae0d2 url("images/bg.gif") repeat-x bottom; border: 1px thin'>
<tbody>
<tr>
<td>
<div id="userDetails">
<center>
<table>
<tbody>
<tr class="EbTopBar">
</tr>
<tr class="EbTopBar">
<td align="right" width="100"><label class="TextLabel1">UserId :</label></td>
<td width="110"><input type="text" name="userID" value=""
class="EbInputBg" size="15" tabindex="1"></td>
</tr>
<tr class="EbTopBar">
<td align="right" width="100"><label class="TextLabel1">Password :</label></td>
<td width="110"><input type="password" name="password" value=""
class="EbInputBg" size="15" tabindex="2"></td>
</tr>
</tbody>
</table>
</center>
</div>
</td>
</tr>
<tr>
<td>
<div style="display:" id="vanisher">
<center>
<table>
<tbody>
<tr class="EbTopBar">
<td align="right" width="100"><label class="TextLabel1">Location</label></td>
<td width="110"><select id="userLocale" name="userLocale"
class="ComboBox_ID12">
<OPTION value="US CA" >US CA</OPTION>
<OPTION value="FR" >FR</OPTION>
<OPTION value="AU" >AU</OPTION>
<OPTION value="SNG" >SNG</OPTION>
<OPTION value="LNC" >LNC</OPTION>
</select></td>
</tr>
<tr class="EbTopBar">
<td align="right" width="100"><label class="TextLabel1">Business Unit</label></td>
<td width="110"><select id="userBU" name="userBU"
class="ComboBox_ID12">
<OPTION value="LNC" >LNC</OPTION>
<OPTION value="COS" >COS</OPTION>
<OPTION value="MI" >MI</OPTION>
<OPTION value="MB" >MB</OPTION>
<OPTION value="MDC-SNG" >MDC-SNG</OPTION>
<OPTION value="LNFR" >LNFR</OPTION>
</select></td>
</tr>
<tr class="EbTopBar">
<td/>
<td align="left" width="100"><label class="TextLabel1">Correct business unit must be selected</label></td>
</tr>
</tbody>
</table>
</center>
</div>
</td>
</tr>
<!--
<TR>
<TD CLASS="link"><A HREF="javascript:dispHandle(vanisher)">Choose
Language </A></TD>
</TR>
-->
<tr>
<td>
<center>
<table>
<tbody>
<tr>
<td align="right" width="100"><label class="TextLabel1">Platform :</label></td>
<td width="110"><input type="text" name="servName" value=""
class="EbReadOnly" size="15" tabindex="3" readonly></td>
</tr>
<tr>
<td align="right" width="100"></td>
<!--
<TD WIDTH="110"><INPUT TYPE="checkbox" NAME="rememberme" VALUE="N"
ONCLICK="rememberMe(this);"><LABEL CLASS="TextLabel1">Remember Me</LABEL></TD>
-->
</tr>
</tbody>
</table>
</center>
</td>
</tr>
<tr>
<td>
<center>
<table id="loginButtons">
<tbody>
<tr>
<td width="80"></td>
<td><input type="submit" name="login"
value='Login'
onclick="submitForm()" class="EbButton" /></td>
<td><input type="reset" name="cancel"
value='Cancel' class="EbButton" /></td>
<td width="80"></td>
</tr>
</tbody>
</table>
</center>
</td>
</tr>
</tbody>
</table>
</center>
<input type="hidden" name="rememberFlag" value="false">
<center>Login problems?<br>
</center>
<center>
<table border="1">
<tbody align="center">
<tr>
<td align="center">English</td>
<td align="center"><a href="javascript:setUserLocale('FR', 'LNFR')";>Français</a></td>
</tr>
</tbody>
</table>
</center>
<input name="hiddenHost" type="hidden" value='cpc44743'/>
</form>
</body>
</html>

How do I use Flask to show a generated matplotlib image on the same screen as the form?

Basically I am using matplotlib to generate charts that I want to then display directly to the user. The user fills out a form and the variables are passed to a few methods that create the chart. The code I currently have will show only the image and get rid of the form. Is it possible to display the image on the page so that the user can modify the queries/connections and see the results with each subsequent form submission?
Here is my code:
from flask import Flask, request, render_template, send_file, redirect, url_for
import flask
import MultipleDatabasesLib as mdl
import subprocess
import pandas as pd
import matplotlib as plt
from matplotlib import pyplot as plt
app = Flask(__name__)
xlabel = ""
ylabel = ""
graph_title = ""
#app.route('/')
def my_form():
return render_template('my-form.html')
#app.route('/get_form_vals', methods=['POST', 'GET'])
def form_vals():
df = pd.DataFrame()
df_group = pd.DataFrame()
fig_size = plt.rcParams["figure.figsize"]
fig_size[0] = 15
fig_size[1] = 12
plt.rcParams["figure.figsize"] = fig_size
base = "C:/Python36-32/GraphFactory/Final_csv.csv"
conn1 = flask.request.args.get('conn1')
conn2 = flask.request.args.get('conn2')
sql1 = flask.request.args.get('sql1')
sql2 = flask.request.args.get('sql2')
charttype = flask.request.args.get('charttype')
xlabel = flask.request.args.get('xLabel')
ylabel = flask.request.args.get('yLabel')
groupBy = flask.request.args.get('groupBy')
#graph_title = charttype + "Chart"
mdl.gen_csv(conn1, conn2, sql1, sql2)
df = pd.read_csv(base)
df_group = df.groupby(['YR', 'INSTANCE']).size()
if charttype == "bar":
mdl.bar_plot(xlabel, ylabel, 'Plot', df_group)
elif charttype == "pie":
mdl.pie_plot(xlabel, ylabel, 'Plot', df_group)
elif charttype == "line":
mdl.line_plot(xlabel, ylabel, 'Plot', df_group)
elif charttype == "hist":
mdl.hist_plot(xlabel, ylabel, 'Plot', df_group)
#return send_file("plt.png", mimetype='image/gif')
return flask.jsonify({"result":"<div class='user_avatar' style='background-image:url('/static/images/figure.png');width:240px;height:240px;background-size:cover;border-radius:10px;'>"})
app.run(host='0.0.0.0', port=33)
HTML:
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" href="/static/my-css.css">
<head>
<meta charset="UTF-8">
<title>Graph Factory</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<table class="headerTable" background="https://crunchify.com/bg.png" width="100%">
<tr>
<td width="95%"><img src="static/SEILogo.png" /></td>
</tr>
</table>
<table style="width:50%" class="inputForm" align="center" cellspacing="0">
<tr>
<th>
Connection
</th>
<th>
Query
</th>
</tr>
<tr>
<td align="center">
<input type="text" name="conn1" id="conn1"/>
</td>
<td align="center">
<textarea name="sql1" cols="70" rows="8" id="sql1"></textarea>
</td>
</tr>
<tr>
<td align="center">
<input type="text" name="conn2" id="conn2"/>
</td>
<td align="center">
<textarea name="sql2" cols="70" rows="8" id="sql2"></textarea>
</td>
{#<td align="left">
Export CSV
</td>#}
</tr>
<tr class="top row">
<td align="center">
<label>X-axis Label</label>
</td>
<td align="center">
<input type="text" name="xLabel" id="xLabel"/>
</td>
</tr>
<tr>
<td align="center">
<label>Y-axis Label</label>
</td>
<td align="center">
<input type="text" name="yLabel" id="yLabel"/>
</td>
</tr>
<tr>
<td align="center">
<label>Group by Parameter</label>
</td>
<td align="center">
<input type="text" name="groupBy" id="groupBy"/>
</td>
</tr>
<tr>
<td align="center">
<label>Graph Type</label>
</td>
<td align="center">
<select name="charttype" id="dropdownchart">
<option value="bar">Bar</option>
<option value="pie">Pie</option>
<option value="line">Line</option>
<option value="hist">Hist</option>
</select>
</td>
</tr>
<tr>
<td colspan="20" align="center">
<button type='button' class='get_result'>Show Graph</button>
</td>
</tr>
</table>
<div id='image_location'></div>
<script>
$(document).ready(function() {
$('.get_result').click(function(){
var conn1 = $('#conn1').val();
var conn2 = $('#conn2').val();
var sql1 = $('#sql1').val();
var sql2 = $('#sql2').val();
var xlabel = $('#xLabel').val();
var ylabel = $('#yLabel').val();
var groupBy = $('#groupBy').val();
var dropdownchart = $('#dropdownchart').val();
$.ajax({
url: "/get_form_vals",
type: "get",
data: {conn1: conn1, conn2:conn2, sql1:sql1, sql2:sql2, xlabel:xlabel, ylabel:ylabel,
groupBy:groupBy, dropdownchart:dropdownchart},
success: function(img) {
$("#image_location").html(img.result);
},
error: function(xhr) {
print("error")
}
});
});
});
</script>
</body>
</html>
You will have to use flask with ajax. To do that, you will need to create a separate route to create the graph, savee the file, and return the HTML with the link to the image. Below is a slightly shortened solution showing how this can be done. Ensure that you have a static/images directory created, with static at the same level as templates/ in your application folder:
in main_app.py:
import matplotlib.pyplot as plt
import flask
app = flask.Flask(__name__
#app.route('/', methods=['GET'])
def home():
return render_template('my-form.html')
#app.route('/get_form_vals')
def form_vals():
conn1 = flask.request.args.get('conn1')
conn2 = flask.request.args.get('conn2'])
#rest of vals follow
plt.plot(x, y) #formulate your x, y values before
plt.savefig('/app/static/images/filenameXYZ.png') #save to the images directory
return flask.jsonify({"result":"<div class='user_avatar' style='background-image:url('/static/images/figure.png');width:240px;height:240px;background-size:cover;border-radius:10px;'>"})
Then, in my-form.html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<input type='text' id='conn1'>
<input type='text' id='conn2'>
<!--rest of inputs follow -->
<button type='button' class='get_result'></button>
<div id='image_location'></div>
<script>
$(document).ready(function() {
$('.get_result').click(function(){
var conn1 = $('#conn1').val();
var conn2 = $('#conn2').val();
//get the rest of the vals
$.ajax({
url: "/get_form_vals",
type: "get",
data: {conn1: conn1, conn2:conn2}, //fill out rest of object
success: function(response) {
$("#image_location").html(response.message);
},
error: function(xhr) {
//Do Something to handle error
}
});
});
});
</script>
</html>

How to select radio buttons and submit a form

This is the HTML:
<form method="post" action="./xxxxx" name="form1">
<input type="hidden" name="requestKey" value="52032a76cf53340b07052fd143feddc4a9d8f18130c80ec86003ab56e0d91b36"/>
<input type="hidden" name="option" value="txnlist">
<input type="hidden" name="account" value='1336169999'>
<input type="hidden" name="app" value="D">
<input type="hidden" name="lockType" value="">
<p><span class="header2"> Statement options </span>
<table summary="" width="100%" border="0" cellpadding="1" cellspacing="1">
<tr>
<td width="20"></td>
<td width="20"><input type="radio" name="optDateFilter" value="1"></td>
<td>Transactions for the last 30 days</td>
<td></td>
</tr>
<tr>
<td width="20"></td>
<td width="20"><input type="radio" name="optDateFilter" value="2"></td>
<td>Transactions for the last 90 days</td>
<td></td>
</tr>
<tr>
<td width="20"> </td>
<td width="20"><input type="radio" name="optDateFilter" checked='checked' value="3" style="vertical-align: middle"></td>
<td>
<div>
<font style="vertical-align: middle;">Transactions from </font>
<script src='jquery/js/ui/min/jquery.ui.datepicker.min-1.8.10.js'></script>
<script type='text/javascript'>$(function() {$('#datepicker1').datepicker( { changeMonth : true, changeYear : true, dateFormat : 'dd/mm/yy', showOn: 'both', buttonImage: 'images/calendar.png', buttonImageOnly: true }); }); </script>
<input type='text' id='datepicker1' name='txtFromDate' size='11' maxlength='10' value='14/12/2012' onchange="checkFromDate(document.form1.txtFromDate.value);document.form1.optDateFilter[2].checked = true;">
<font style="vertical-align: middle;">to</font>
<script type='text/javascript'>$(function() {$('#datepicker2').datepicker( { changeMonth : true, changeYear : true, dateFormat : 'dd/mm/yy', showOn: 'both', buttonImage: 'images/calendar.png', buttonImageOnly: true }); }); </script>
<input type='text' id='datepicker2' name='txtToDate' size='11' maxlength='10' value='01/01/2013' onchange="checkToDate(document.form1.txtFromDate.value,document.form1.txtToDate.value);document.form1.optDateFilter[2].checked = true;">
</div>
</td>
<td><font style="font-size: 8pt; vertical-align: middle;"><i>(maximum date range 3 months)</i></font></td>
</tr>
</table>
<table summary="" cellpadding="1" cellspacing="1" border="0">
<tr>
<td width="20"> </td>
<td width="20">
<a href="javascript:if(document.form1.optDateFilter[2].checked==true){CheckAndSubmit(document.form1.txtFromDate.value,document.form1.txtToDate.value);}else{showOverlay();document.form1.submit();};">
<img src="images/proceed.gif" alt="Show the selected range of transactions" border="0" width="22" height="22" />
</a>
</td>
<td>
Show the selected range of transactions
</td>
</tr>
</table>
</form>
This is the code i have, and it is not working:
self.browser.select_form('form1')
self.browser.form.set_all_readonly(False)
self.browser['txtFromDate'] = '28/12/12'
self.browser['txtToDate'] = '01/01/13'
resp = self.browser.submit()
html = resp.read()
I figured that i had to do this
self.browser.select_form('form1')
self.browser['optDateFilter'] = ['2']
self.browser.form.find_control(name="txtFromDate", id="datepicker1").value = "13/10/12"
self.browser.form.find_control(name="txtToDate", id="datepicker2").value = "01/01/13"
resp = self.browser.submit()
mechanize has a strange quirk: since there can be multiple radio button elements in a HTML document with the same name it insists that you use a list as value, even though only a single radio button may be selected at any time. That means that you need to use this:
self.browser.form.find_control(name='optDateFilter').value = ['2']
The same holds for checkboxes where it makes more sense because a user is allowed to select multiple values.

Categories