上一篇:Vue 2.0 起步(4)第二版 轻量级后端Flask用户认证 - 微信公众号RSS
用户在本地搜索、订阅了公众号以后,可以方便地上传订阅列表到服务器上。也可以在另一地方下载订阅列表到本地
完成图:点击上传、下载图标就行
步骤:
- 后端Flask models更新
- api支持订阅列表上传、下载
- 前端vue.js ajax上传、下载订阅列表
1. 后端Flask models更新
Mp模型,添加to_json、from_json方法,分别对应ajax下载、上传来返回数据库查询。
注意from_json,用户上传是一个订阅列表,json里面包含多个mp,所以返回的是一个Mp模型的数组
/app/models.py
# 公众号
class Mp(db.Model):
__tablename__ = 'mps'
id = db.Column(db.Integer, primary_key=True)
weixinhao = db.Column(db.Text)
image = db.Column(db.Text)
summary = db.Column(db.Text)
sync_time = db.Column(db.DateTime, index=True, default=datetime.utcnow) # Search.vue: date
mpName = db.Column(db.Text)
encGzhUrl = db.Column(db.Text) # 临时主页
subscribeDate = db.Column(db.DateTime())
# 如果加了dynamic, Flask-Admin里会显示raw SQL
articles = db.relationship('Article', backref='mp', lazy='dynamic')
subscribers = db.relationship('Subscription',
foreign_keys=[Subscription.mp_id],
backref=db.backref('mp', lazy='joined'),
lazy='dynamic',
cascade='all, delete-orphan')
def to_json(self):
json_mp = {
'weixinhao': self.weixinhao,
'mpName': self.mpName,
'image': self.image,
'summary': self.summary,
'subscribeDate': self.subscribeDate,
'articles_count': self.articles.count()
}
return json_mp
@staticmethod
def from_json(json_post):
mps = json_post.get('mps')
print mps
if mps is None or mps == '':
raise ('POST does not have mps')
Mps = []
for mp in mps:
# print mp
Mps.append( Mp(mpName=mp['mpName'], image=mp['image'], weixinhao=mp['weixinhao'] ) )
return Mps
2. api支持订阅列表上传、下载
用户使用POST上传列表,带email、mps参数
- api取得email参数,来查询User已经订阅的Mps。
- Mp.from_json()把json.mps,转换成Mp模型列表
- 如果不存在这个订阅号,则添加到Mp,并订阅
- 如果用户没有订阅,则订阅
/app/api_1_0/mps.py
from flask_security import auth_token_required
@api.route('/mps', methods=['POST'])
@auth_token_required
def new_mps():
email = request.get_json()['email']
user = User.query.filter_by(email=email).first()
Mps = Mp.from_json(request.json)
subscribed_mps_weixinhao = [i.weixinhao for i in user.subscribed_mps]
rsp = []
for mp in Mps:
mp_sql = Mp.query.filter_by(weixinhao=mp.weixinhao).first()
# 如果不存在这个订阅号,则添加到Mp,并订阅
if mp_sql is None:
db.session.add(mp)
user.subscribe(mp)
rsp.append(mp.to_json())
db.session.commit()
# 如果用户没有订阅,则订阅
elif not mp.weixinhao in subscribed_mps_weixinhao:
user.subscribe(mp_sql)
rsp.append(mp.to_json())
db.session.commit()
return jsonify(rsp), 201, \
{'Location': url_for('api.get_mps', id=mp.id, _external=True)}
用户下载订阅列表,使用GET。服务器拿到email后,通过SQLAlchemy过滤器和联结查询,返回subscribed_mps
# 带 /mps/ 斜杠的,必须放在 /mps POST后面,不然默认会选择以下GET
@api.route('/mps/')
@auth_token_required
def get_mps():
# request.args.items().__str__()
email = request.args.get('email')
print email
mps = User.query.filter_by(email=email).first().subscribed_mps
mps_list = [ mp.to_json() for mp in mps ]
print mps_list
return jsonify(mps_list)
3. 前端vue.js ajax上传、下载
/src/components/Siderbar.vue
上传函数uploadSubscription(),ajax POST请求头:注意Authentication-Token,Content-Type参数
json参数带上email, mps
服务器响应201,以及新添加的mps
uploadSubscription() {
if (this.subscribeList.length === 0) return false;
this.$http.post('/api/v1.0/mps',
//body
{
email: this.username,
mps: this.subscribeList
},
//options
{
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'Authentication-Token': this.token
}
}).then((response) => {
// 响应成功回调
var data = response.body,
mp;
alert('成功上传订阅号:\n' + JSON.stringify(data))
}, (response) => {
// 响应错误回调
alert('同步出错了! ' + JSON.stringify(response))
if (response.status == 401) {
alert('登录超时,请重新登录');
this.is_login = false;
this.password = '';
window.localStorage.removeItem("user")
}
});
},
下载函数getSubscription(),GET url编码为:http://localhost:5000/api/v1.0/mps/?email=admin。
对于服务器返回的json,是一个数组:
Vue先要清空当前本地订阅列表,然后逐个订阅从服务器取回的Mp
getSubscription() {
this.$http.get('/api/v1.0/mps', {
params: {
email: this.username
},
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'Authentication-Token': this.token
}
}).then((response) => {
// 响应成功回调
var data = response.body,
mp, found_tag = false;
alert('订阅号 from server:\n' + JSON.stringify(data));
for (let item of this.subscribeList) {
this.$store.dispatch('unsubscribeMp', item.weixinhao);
}
this.$store.dispatch('clearSubscription', 'get sublist from Server');
for (let mp of data) {
mp['showRemoveBtn'] = false;
this.$store.dispatch('subscribeMp', mp);
}
}, (response) => {
// 响应错误回调
alert('同步出错了! ' + JSON.stringify(response))
if (response.status == 401) {
alert('登录超时,请重新登录');
this.is_login = false;
this.password = '';
window.localStorage.removeItem("user")
}
});
}
OK,试试吧:
Demo:http://vue2.heroku.com
源码:https://github.com/kevinqqnj/vue-tutorial
请使用新的template: https://github.com/kevinqqnj/flask-template-advanced
下一篇:Vue 2.0 起步(6) 后台管理Flask-Admin - 微信公众号RSS
http://www.jianshu.com/p/ab778fde3b99