這是一個燒瓶應用程式
使用此鏈接運行應用程式:(將 XXX 替換為您的機器 url)http://XXX.0.0.1:5050/?tickers_get=Company2&open_price_get=23
我正在嘗試的是,當用戶從下拉串列中選擇 Company2 時,另一個下拉串列應該更新為只有 2 個價格(22 和 40),而無需點擊提交按鈕。然后當用戶點擊提交按鈕時,表格應該按照
應用程式.py
from flask import Flask, render_template, request
import pandas as pd
import sqlalchemy as sal
from sqlalchemy import create_engine
import pyodbc
import urllib
import numpy as np
app = Flask(__name__)
get_data_through = "manual_entry"
@app.route('/')
def index():
read_df = pd.DataFrame(
[
['Company1', 23, 10000],
['Company2', 22, 40000],
['Company2', 40, 40000]
],
columns=['new_sql_table','Open_price', 'volume']
)
names = set(read_df['new_sql_table'].tolist())
tickers = request.args.getlist('tickers_get')
#tickers_get_to_string = ''.join(tickers) # to convert to string
#open_price_to_filter = np.arange(1000).tolist()
open_price_to_filter = read_df['Open_price'].tolist()
open_price = request.args.getlist('open_price_get')
print(open_price)
open_price_get_to_number = ''.join(open_price)
data = read_df[read_df['new_sql_table'].isin(tickers)]
sum_of_volumns = format(sum(data['volume']), ',')
return render_template('template.html', **locals())
if __name__ == "__main__":
app.run(port = 5050)
模板.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='styles/mainpage.css') }}">
<title>Stocks data</title>
</head>
<body>
<h2>Stocks data</h2><h4>Total Volume is : {{sum_of_volumns}} and selected open price is {{open_price_get_to_number}}</h4>
<form>
<label>Company:</label>
<select name="tickers_get">
{% for name in names %}
<option value="{{ name }}" {% if name in tickers %}selected{% endif %}>{{name}}</option>
{% endfor %}
</select>
<label>Open Price:</label>
<select name="open_price_get" style="width:75px">
{% for op in open_price_to_filter %}
<option value="{{ op }}" {% if op in open_price %}selected{% endif %}>{{op}}</option>
{% endfor %}
</select>
<button type="submit">Submit</button>
</form>
<hr/>
<table border="2" width="100%">
<thead>
<tr>
{% for column in data.columns %}
<th>{{ column }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for row in data.values %}
<tr style="text-align:center">
{% for cell in row %}
<td>{{ cell }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
我無法在第二個過濾器中獲得動態下拉串列
uj5u.com熱心網友回復:
為了根據第一個選擇框動態填充第二個選擇框,您需要 JavaScript。
在下面的示例中,為第一個輸入欄位注冊了一個事件偵聽器,它回應型別更改的事件。如果該欄位內的選擇發生變化,則從第二個端點異步獲取所需資料并插入到第二個輸入欄位中。Fetch API用于此目的,它以 JSON 格式接收資料。
股票代碼將通過 GET 請求以逗號分隔的字串形式發送。這意味著這些作為 URL 引數傳輸,即附加到 URL。使用查詢request.arg.get(...),值會根據它們的名稱進行查詢。默認為空串列。在 lambda 運算式中,字串用逗號分隔,空值通過回圈過濾掉。您將獲得一個股票代碼串列。
symbols = request.args.get(
'symbols', # Name of parameter
[], # Default return value
type=lambda x: [y for y in x.split(',') if y] # Split by ',' and filter empty strings
)
然后將串列中包含“符號”列的所有行從 DataFrame 中過濾掉。“開盤價”列是從這些行中提取的,并且任何重復都會被一組阻止。
open_prices = set(df[df['Symbol'].isin(symbols)]['Open Price'].tolist())
最后,接收到的價格作為 JSON 格式的串列回傳,包含在稱為“items”的嵌套結構中。
return jsonify(items=list(open_prices))
最終發送表單時,從 DataFrame 中過濾出顯示所需的資料并傳遞給模板。
from flask import (
Flask,
jsonify,
render_template,
request
)
import pandas as pd
df = pd.DataFrame(
[
['Company1', 23, 10000],
['Company2', 22, 40000],
['Company2', 40, 40000],
],
columns=['Symbol','Open Price', 'Volume']
)
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
symbols = set(df['Symbol'].tolist())
open_prices = set(df['Open Price'].tolist())
sel_symbols = symbols
sel_open_prices = open_prices
if request.method == 'POST':
sel_symbols = request.form.getlist('symbols')
sel_open_prices = request.form.getlist('open-prices', type=int)
open_prices = set(df[df['Symbol'].isin(sel_symbols)]['Open Price'].tolist())
data = df[df['Symbol'].isin(sel_symbols)][df['Open Price'].isin(sel_open_prices)]
total_volumes = sum(data['Volume'])
return render_template('index.html', **locals())
@app.route('/open-prices')
def open_prices():
symbols = request.args.get('symbols', [], type=lambda x: [y for y in x.split(',') if y])
open_prices = set(df[df['Symbol'].isin(symbols)]['Open Price'].tolist())
return jsonify(items=list(open_prices))
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Index</title>
<style type="text/css">
table, th, td {
border: 1px solid #9a9a9a;
border-collapse: collapse;
padding: .64rem;
}
th {
border-bottom: 2px solid #9a9a9a;
}
select {
width: 75px;
}
</style>
</head>
<body>
<form method="POST">
<label for="symbols">Symbol</label>
<select name="symbols" id="symbols" multiple>
{% for symbol in symbols -%}
<option value="{{ symbol }}" {% if symbol in sel_symbols %}selected{% endif %}>{{ symbol }}</option>
{% endfor -%}
</select>
<label for="open-prices">Open Price</label>
<select name="open-prices" id="open-prices" multiple>
{% for price in open_prices -%}
<option value="{{ price }}" {% if price in sel_open_prices %}selected{% endif %}>{{ price }}</option>
{% endfor -%}
</select>
<button type="submit">Submit</button>
</form>
<hr />
{% if data.values | count -%}
<h4>Total Volume is {{total_volumes}} and selected
{{ 'are' if sel_open_prices | count > 1 else 'is'}}
{{ sel_open_prices | join(', ') }}.
</h4>
<table width="100%">
<thead>
<tr>
{% for column in data.columns %}
<th>{{ column }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for row in data.values %}
<tr style="text-align:center">
{% for cell in row %}
<td>{{ cell }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
{% else -%}
<p>No items found.</p>
{% endif -%}
<script type="text/javascript">
(function(url) {
const priceSelect = document.querySelector('select[name="open-prices"]');
const tickerSelect = document.querySelector('select[name="symbols"]');
tickerSelect && tickerSelect.addEventListener('change', function(event) {
// Get selected items.
let optionsSelected = [];
let options = event.target.options;
for (let opt of options) {
if (opt.selected) {
optionsSelected.push(opt.value || opt.text);
}
}
// Send AJAX request to the server.
fetch(`${url}?symbols=${encodeURIComponent(optionsSelected.join(','))}`)
.then(resp => resp.ok && resp.json())
.then(data => {
// Add the entries to the input field.
priceSelect && (priceSelect.innerHTML = data.items.map(item => {
return `<option value="${item}" selected>${item}</option>`;
}).join(''))
});
});
})({{ url_for('open_prices') | tojson }});
</script>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/525188.html
標籤:Python烧瓶
下一篇:jinja2.exceptions.UndefinedError:'forms.SignupFormobject'沒有屬性'hidden_??tag'
