比妹子网站后端使用python的web框架flask,为什不用Django呢?因为最近看了看Flask的document,强行使用一下吧。可以看出,这个框架安全性简直为0!
###数据库模块
使用Sqlite3数据库,就是一个小表~ 表格如下:
drop table if exists picture; create table picture( id integer primary key autoincrement, name text unique not null, support integer default 0 );
app = Flask(__name__) app.config.from_object(__name__) #Configuration app.config.update(dict( DATABASE = os.path.join(app.root_path, 'meizi.db'), DEBUG = True, )) #DATEBASE def init_db(): with app.app_context(): db = get_db() with app.open_resource('meizi.sql', mode = 'r') as f: db.cursor().executescript(f.read()) db.commit() def connect_db(): rv = sqlite3.connect(app.config['DATABASE']) return rv def get_db(): if not hasattr(g, 'sqlite_db'): g.sqlite_db = connect_db() return g.sqlite_db def close_db(): if hasattr(g, 'sqlite_db'): g.sqlite_db.close()
###首页+功能展示
首页就是两个图片,对比一下,选择一个喜欢的,点击。涉及数据库随机出来两个图片,使用 order by randon() 语句实现就行。
鼠标点击事件,传回来点击图片的id,然后在数据库端增加个支持率。
还有Top10, random ,无非是返回前十个照片数据库信息和随机几个照片信息。
@app.route('/', methods = ['get', 'post']) def index(): db = connect_db() cur = db.execute('select * from picture order by RANDOM() limit 2') return render_template('index.html', lists = (cur.fetchall())) @app.route('/click', methods = ['post']) def click(): db = connect_db() logger.error(request.form) if request.form['pic_id'] is not None: db.execute('update picture set support = support + 2 where id = %d' \ %int(request.form['pic_id'])) logger.error(request.form['pic_id']) db.commit() cur = db.execute('select * from picture order by RANDOM() limit 2').fetchall() ret = {} ret['p1'] = cur[0][1] ret['p1_id'] = cur[0][0] ret['p2'] = cur[1][1] ret['p2_id'] = cur[1][0] logger.error(ret) return jsonify(ret) @app.route('/top') def top10(): db = connect_db() lists = db.execute('select * from picture order by support desc limit 10') return render_template('top.html', lists = lists.fetchall()) @app.route('/random') def random_pic(): db = connect_db() lists = db.execute('select * from picture order by RANDOM() limit 28') return render_template('random.html', lists = lists.fetchall())