之前那篇文章是flask+redis的,如果用flask+mysql怎么实现呢?
创建数据库:CREATE DATABASE `web12306` DEFAULT CHARACTER SET utf8; 创建表:CREATE TABLE `web12306` (
`user_email` varchar(100) NOT NULL DEFAULT '',
`user_pass` varchar(100) NOT NULL DEFAULT '',
`user_name` varchar(100) NOT NULL DEFAULT '',
`user_id` varchar(100) NOT NULL DEFAULT '',
`user_nic` varchar(100) NOT NULL DEFAULT '',
`user_phone` varchar(100) NOT NULL DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8; 导入数据,数据文件还是result.txt,同样的格式。mysql -uroot -pmysql@123 -e 'load data local infile "result.txt" into table web12306.web12306 fields terminated by "---" lines terminated by "\n";'
查看数据导入情况:
数据有了,剩下还是上python代码了,使用mysql时,需要用到sqlalchemy# -*- coding: utf-8 -*-
from flask import Flask, request, render_template, jsonify, json
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:mysql@123@localhost/web12306'
class session(db.Model):
__tablename__ = 'web12306'
user_id = db.Column(db.String(100), primary_key = True)
user_email = db.Column(db.String(100))
user_pass = db.Column(db.String(100))
user_nic = db.Column(db.String(100))
user_phone = db.Column(db.String(100))
user_name = db.Column(db.String(100))
@app.route('/scan/<user_id>', methods=['GET'])
def scan(user_id):
result = session.query.filter_by(user_id=user_id).first()
if result is None:
json_result={'user_id':None}
return json.dumps(json_result,ensure_ascii=False)
else:
json_result = {'user_id': result.user_id, 'user_email': result.user_email, 'user_pass': result.user_pass, 'user_nic': result.user_nic, 'user_phone': result.user_phone, 'user_name': result.user_name}
return json.dumps(json_result,ensure_ascii=False)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(host='0.0.0.0', port = 8080, debug=True) 前端代码请看上一篇文字。
|