import pymysql from datetime import datetime, timedelta import time class MyDB: def __init__(self, host, user, passwd, db): self.conn = pymysql.connect(host, user, passwd, db) self.cursor = self.conn.cursor() def __del__(self): self.conn.close() # 获取当然日期 def get_cur_date(self): date = datetime.today() curdate = date.strftime('%Y.%m.%d') return curdate # 获取前N天的日期 def get_pren_date(self, n=1): predate = datetime.today() + timedelta(-n) predate = predate.strftime('%Y.%m.%d') return predate # 获取现有确诊人数最多的5个国家 def get_country_curconfirm_top5(self): curdate = self.get_cur_date() # 获取当天的日期 sql = "select area,curConfirm,pub_date from foreign_daily_datas where pub_date like '%s' order by curConfirm desc limit 5" % (curdate + '%') #print('+++ sql: %s' % sql) results = [] try: self.cursor.execute(sql) results = self.cursor.fetchall() n = 1 while len(results) <= 0: predate = self.get_pren_date(n) sql = "select area,curConfirm,pub_date from foreign_daily_datas where pub_date like '%s' order by curConfirm desc limit 5" % (predate + '%') #print('+++ presql: %s' % sql) self.cursor.execute(sql) results = self.cursor.fetchall() n += 1 if n >= 30: break else: time.sleep(1) except Exception as e: print(e) return results #测试 if __name__ == "__main__": mydb = MyDB('localhost', 'root', '1999z5g24x', 'text_data_increasing') results = mydb.get_country_curconfirm_top5() # results : [] for i in results: print(i) from flask import Flask, render_template from flask import jsonify app = Flask(__name__) @app.route('/hello') def say_hello(): return '

Hello World

' @app.route('/') def hello(): return render_template('we_text.html', name='Jerry') @app.route('/country_topn_curconfirm') def get_country_curconfirm_topn(): mydb = MyDB('localhost', 'root', '1999z5g24x', 'text_data_increasing') results = mydb.get_country_curconfirm_top5() # results : [] return jsonify(pub_date=results[0][2], country=[x[0] for x in results], curConfirms=[x[1] for x in results]) app.run()