Flask实例——四六级单词表查询
这里我们会链接数据库,并用flask达到输入单词,在网页上返回数据库中查询结果的目的。
Python文件
from flask import Flask, request, render_template, jsonify
from flask_cors import *
import pymysql
app = Flask(__name__,static_url_path='/static/',template_folder='templates')
CORS(app, resources=r'/*')
# 主页
@app.route('/')
def index():
return "Hello!"
# 显示所有的四六级单词的页面路由
@app.route('/englishWord')
def english():
db=pymysql.connect("localhost","root","--密码--","--数据库名--",charset='utf8')
cursor=db.cursor()
try:
sql="select * from map_enword limit 200"
cursor.execute(sql)
rs=cursor.fetchall()
rs=list(rs)
print(rs)
except:
rs='db-error'
print('py-db-error')
db.close()
return render_template('englishWord.html',rs=rs)
# 查询页面路由
@app.route('/search')
def search():
wanted=request.args.get("wanted",type=str)
if wanted == None:
wanted='pineapple'
db=pymysql.connect("localhost","root","--密码--","--数据库名--",charset='utf8')
cursor=db.cursor()
try:
sql="select * from map_enword where english like '%"+wanted+"%' "
cursor.execute(sql)
rs=cursor.fetchall()
rs=list(rs)
print(rs)
except:
rs='db-error'
print('py-db-error')
db.close()
return render_template('search.html',rs=rs)
if __name__ == '__main__':
app.debug=True
app.run('127.0.0.1', 5000)
englishWord.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>四六级单词</title>
</head>
<body>
四六级单词:<br>
<!--{{rs}}-->
{% for r in rs %}
{{r}} <br>
{% endfor %}
</body>
</html>
search.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>四六级单词查询</title>
</head>
<body>
四六级单词查询:<br>
<form action ="/search">
<input type='text' name="wanted" value="" default="apple">
<input type="submit" value="搜索">
</form>
{% for r in rs %}
{{r}} <br>
{% endfor %}
</body>
</html>
结果