flask 与小程序 会员拦截器和分享保存功能

web/interceptors/ApiAuthInterceptor.py

# -*- coding: utf-8 -*-
from application import app
from flask import request,g,jsonify

from common.models.member.Member import Member
from common.libs.member.MemberService import MemberService
import  re

'''
api认证
'''
@app.before_request
def before_request_api():
    api_ignore_urls = app.config['API_IGNORE_URLS']

    path = request.path
    if '/api' not in path:
        return

    member_info = check_member_login()
    g.member_info = None
    if member_info:
        g.member_info = member_info

    pattern = re.compile('%s' % "|".join( api_ignore_urls ))
    if pattern.match(path):
        return

    if not member_info :
        resp = {'code': -1, 'msg': '未登录~', 'data': {}}
        return jsonify(resp)

    return


'''
判断用户是否已经登录
'''
def check_member_login():
    auth_cookie = request.headers.get("Authorization")

    if auth_cookie is None:
        return False

    auth_info = auth_cookie.split("#")
    if len(auth_info) != 2:
        return False

    try:
        member_info = Member.query.filter_by(id=auth_info[1]).first()
    except Exception:
        return False

    if member_info is None:
        return False

    if auth_info[0] != MemberService.geneAuthCode( member_info ):
        return False

    if member_info.status != 1:
        return False

    return member_info

flask网页制作拦截器的时候通过对网页的cookie进行获取和判断,例如 cookie值是不是合法的、是否正确符合格式等,小程序里不能做cookie,这该怎么办呢?

在每次请求的时候都会wx.request请求加载里面的header头部,可以在header头部里面加入一个信息,web取到就可以了。

在mina/app.js

中定义一个Authrization

    getRequestHeader:function(){
        return {
            'content-type': 'application/x-www-form-urlencoded',
            'Authorization': this.getCache("token")
        }
    },

登录时有个cache,存储里有个token,

每次登录的时候都会cache一个信息,取出Authorization值就可以了。

config/base_setting.py

哪些页面不登陆也可以访问的?


API_IGNORE_URLS = [
    "^/api"
]

www.py

'''
统计拦截器
'''
from web.interceptors.AuthInterceptor import  *
from web.interceptors.ApiAuthInterceptor import  *

数据库-分享功能

DROP TABLE IF EXISTS `wx_share_history`;

CREATE TABLE `wx_share_history` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `member_id` int(11) NOT NULL DEFAULT '0' COMMENT '会员id',
  `share_url` varchar(200) NOT NULL DEFAULT '' COMMENT '分享的页面url',
  `created_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='微信分享记录';
flask-sqlacodegen 'mysql://root:[email protected]/food_db' --tables wx_share_history --outfile "common/models/food/WxShareHistory.py"  --flask

web/controllers/api/Member.py

@route_api.route("/member/share",methods = [ "POST" ])
def memberShare():
    resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
    req = request.values
    url = req['url'] if 'url' in req else ''
    member_info = g.member_info
    model_share = WxShareHistory()   #初始化数据模型
    if member_info:
        model_share.member_id = member_info.id
    model_share.share_url = url
    model_share.created_time = getCurrentDate()
    db.session.add(model_share)
    db.session.commit()
    return jsonify(resp)

在api拦截器里将用户信息存到了g全局变量中,这样就可以获取到用户信息

mina/pages/food/info.wxml


 
   
   
        
            
                
                    
                
            
        
        
            
                
            
        
   
   
   
        {{info.name}}
        ¥ {{info.price}}
        购买{{info.total_count}}次
        共收到 {{info.comment_count}} 次好评
        
          
          
          分享有赏
        
   
    
        商品介绍