Python Flask:如何在html模板之间路由并显示来自sqlite db的结果?
我是Flask的新手,正在尝试将路由从Python Flask:如何在html模板之间路由并显示来自sqlite db的结果?,python,sqlite,flask,Python,Sqlite,Flask,我是Flask的新手,正在尝试将路由从home.html添加到results.html,并以html而不是原始json显示结果 使用以下代码,我可以连接到my.db并查询它,例如: 根据post id:127.0.0.1:5000/api/v1/jobs/datascience?Business=ACME筛选条目 api.py: import flask from flask import request, jsonify import sqlite3 import numpy as np
home.html
添加到results.html
,并以html而不是原始json显示结果
使用以下代码,我可以连接到my.db并查询它,例如:
根据post id:127.0.0.1:5000/api/v1/jobs/datascience?Business=ACME筛选条目
api.py
:
import flask
from flask import request, jsonify
import sqlite3
import numpy as np
# Debug allows for changes to be seen in real time.
app = flask.Flask(__name__)
app.config["DEBUG"] = True
def dictFactory(cursor, row):
"""
Function that parses the entries of the database and returns them as a list of dictionaries.
@param cursor -- A cursor object using sqlite.
@param row -- The row of the database being parsed.
"""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
@app.route('/', methods=['GET'])
def homePage():
return '''
<h1>Datascience Jobs Database</h1>
<h3>You have reached: /home/</h3>
<p>To view all entries in the database: '127.0.0.1:5000/api/v1/jobs/datascience/all' </p>
<p>To filter entries based on country : '127.0.0.1:5000/api/v1/jobs/datascience?country=United%20States' </p>
<p>To filter entries based on post id : '127.0.0.1:5000/api/v1/jobs/datascience?id=81953194' </p>
'''
@app.route('/api/v1/jobs/datascience/all', methods=['GET'])
def apiViewAll():
conn = sqlite3.connect('data/datasciencejobs_database.db')
conn.row_factory = dictFactory
cur = conn.cursor()
all_books = cur.execute('SELECT * FROM tblJobs;').fetchall()
return jsonify(all_books)
@app.errorhandler(404)
def pageNotFound(e):
return "<h1>Error 404</h1><p>Page not found.</p>", 404
@app.route('/api/v1/jobs/datascience', methods=['GET'])
def apiViewByFilter():
'''
Function that allows users to filter the results in the API based on specified input.
'''
query_parameters = request.args
id = query_parameters.get('BusinessID')
dateTime = query_parameters.get('date')
cleanContent = query_parameters.get('Business')
country = query_parameters.get('country')
query = "SELECT * FROM tblJobs WHERE"
to_filter = []
if id:
query += ' BusinessID=? AND'
to_filter.append(id)
if dateTime:
query += ' date=? AND'
to_filter.append(dateTime)
if cleanContent:
query += ' Business=? AND'
to_filter.append(cleanContent)
if country:
query += ' country=? AND'
to_filter.append(country)
if not (id or dateTime or cleanContent or country):
return pageNotFound(404)
query = query[:-4] + ';'
conn = sqlite3.connect('data/datasciencejobs_database.db')
conn.row_factory = dictFactory
cur = conn.cursor()
results = cur.execute(query, to_filter).fetchall()
return jsonify(results)
app.run()
home.html
:
<html>
<head>
<title>Main Dashboard</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles/home.css') }}">
<link href="https://fonts.googleapis.com/css2?family=Lato:wght@400;700&display=swap" rel="stylesheet">
</head>
<body>
<h2 class="searchText">Search:</h2>
<form class="searchText" id="searchForm" action="{{ url_for('main_searchPage') }}" method="get">
Business Name: <input class="searchText" id="searchInput" type="text" name="Business"><br>
<input class="searchText" id="searchSubmit" type="submit" value="Submit">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Results Page</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles/results.css') }}">
<link href="https://fonts.googleapis.com/css2?family=Lato:wght@400;700&display=swap" rel="stylesheet">
</head>
<body>
<div id="myResults">
<h3>Your Business {{ Business }}</h3>
<h2>BusinessID {{ BusinessID }}</h2>
<h3>{{ date }}</h3>
<h4>Business Located in: : {{ country }}</h4>
</div>
</body>
</html>
有人能帮我完成以上工作吗,或者至少给我一些关于我应该在代码中修改什么的建议?谢谢 试试这个:
- 将
替换为return jsonify(results)
return render_模板('results.html',results=results)
- 然后在
中将div更改为如下内容:results.html
您的业务{{results.Business}
BusinessID{{results.BusinessID}
{{results.date}
营业地点:{results.country}
此模板部分可能需要进行一些调试,具体取决于结果
的外观,但这就是将数据从flask传递到模板的方式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Results Page</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles/results.css') }}">
<link href="https://fonts.googleapis.com/css2?family=Lato:wght@400;700&display=swap" rel="stylesheet">
</head>
<body>
<div id="myResults">
<h3>Your Business {{ Business }}</h3>
<h2>BusinessID {{ BusinessID }}</h2>
<h3>{{ date }}</h3>
<h4>Business Located in: : {{ country }}</h4>
</div>
</body>
</html>
<div id="myResults">
<h3>Your Business {{ results.Business }}</h3>
<h2>BusinessID {{ results.BusinessID }}</h2>
<h3>{{ results.date }}</h3>
<h4>Business Located in: : {{ results.country }}</h4>
</div>