赞
踩
数据库的内容
from flask import Flask,request from flask import render_template from mysql import Mysql app = Flask(__name__) @app.route('/index') def name(): page = request.args.get('page') if not page or int(page) == 0: page = 1 db = Mysql() keyword = request.args.get('keyword') items = db.getItems(page, keyword) page_range = range(int(page) - 3, int(page) + 2) if int(page) < 4: page_range = range(1, int(page) + 4) return render_template('index.html', items=items,page=int(page),prange = page_range) if __name__ == '__main__': app.run(app.run(debug=True,port=5222,host='127.0.0.1'))
import pymysql class Mysql(object): def __init__(self): try: self.conn = pymysql.connect(host='localhost',user='root',password='fxl395126',database='nba',charset="utf8") self.cursor = self.conn.cursor() # 游标对象 print("连接数据库成功") except: print("连接失败") def getItems(self,page,keyword=None): sql = "select * from news" if keyword: sql = sql + " where title like '%" + keyword + "%'" start = (int(page) - 1) * 10 sql = sql + " limit " + str(start) + ",13" self.cursor.execute(sql) items = self.cursor.fetchall() return items
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="/static/jquery-2.1.4.min.js"></script> <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css"> <script src="/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script> <style> .container{ width: 80%; } </style> </head> <body> <div class="container"> {# 标题#} <h2>篮球新闻</h2> {# 图片#} <div class="col-md-4"> <img src="../static/basketball.jpg" style="height :700px;width:300px;"/> </div> <div class="col-md-8"> {# 搜索关键词#} <div class="row search"> <div class="col-lg-6"> <div class="input-group"> <form action="/index"> <div class="col-lg-9"> <input type="text" class="form-control" name="keyword" placeholder="关键词"> </div> <div class="col-lg-3"> <span class="input-group-btn"> <input class="btn btn-default" type="submit"/> </span></div> </form> </div> </div> </div> {# 新闻列表#} <table class="table mytable-striped"> <thead> <tr> <th>序号</th> <th>标题</th> </tr> </thead> <tbody> {% for item in items %} <tr> <td>{{ item[0]}}</td> <td>{{ item[1]}}</td> </tr> {% endfor %} </tbody> </table> </div> {# 页数#} <nav aria-label="Page navigation"> <ul class="pagination"> <li> <a href="/index?page={{ page - 1 }}" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> {% for pg in prange %} <li><a href="/index?page={{ pg }}">{{ pg }}</a></li> {% endfor %} <li> <a href="/index?page={{ page + 1}}" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> </ul> </nav> </div> </body> </html>
在关键词框输入勇士并提交,我们可以搜索到有关勇士的新闻有4条
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。