Python flask实战订餐系统微信小程序-31定义后端接口接收小程序请求

wechat 虚幻 804℃ 0评论

定义后端接口接收小程序端发送过来的请求

创建member.py接收post請求

20210809185711 - Python flask实战订餐系统微信小程序-31定义后端接口接收小程序请求

from web.controllers.api import route_api
from flask import request,jsonify
from application import app,db

@route_api.route("/member/login", methods = ["GET","POST"])
def login():
    resp = {'code':200, 'msg':'操作成功', 'data':{}}
    req = request.values
    app.logger.info(req)
    return resp

index.js定義請求路徑url

  login:function (e) {
    if(!e.detail.userInfo){
      app.alert({'content':'登录失败,请在此点击'})
    }
    var data = e.detail.userInfo;

    wx.request({
      url: 'http://127.0.0.1:8999/api/member/login',
      method:'POST',
      data: data,
      header: app.getRequestHeader(),
      success:function (res) {

      }
    })
  },

因爲有攔截器 我們需要在在base_setting.py中添加正則過濾

#过滤url
IGNORE_URLS = [
    r"^/user/login",
    r"^/api"
]

__ init __.py中引入Member.py

from flask import Blueprint
route_api = Blueprint( 'api_page',__name__ )
from web.controllers.api.Member import *

@route_api.route( "/" )
def index():
    return "mina Api V1.0"

传递用户的code数据

根据用户的基本信息是无法实现注册的

wx.login 这个接口通过code获取openid

openid是用户的唯一标识。

一个人关注了2个小程序 那么这个人在不同的小程序里面的openid是不一样的

所以可以通过openid判断用户是否已经注册

所以通过code来获取openid,对比这个openid是否在数据库里面 判断这个用户是否已经注册

  login:function (e) {
    if(!e.detail.userInfo){
      app.alert({'content':'登录失败,请在此点击'})
    }
    var data = e.detail.userInfo;

    wx.login({
        success:function (res) {
          if (!res.code){
            app.alert({'content':'登录失败,请在此点击'});
            return
          }
          data['code'] = res.code;

          wx.request({
            url: 'http://127.0.0.1:8999/api/member/login',
            method:'POST',
            data: data,
            header: app.getRequestHeader(),
            success:function (res) {

            }
          })

        }
    });
  },

member.py处理code

from web.controllers.api import route_api
from flask import request,jsonify
from application import app,db

@route_api.route("/member/login", methods = ["GET","POST"])
def login():
    resp = {'code':200, 'msg':'操作成功', 'data':{}}
    req = request.values

    code = req['code'] if 'code' in req else ''
    if not code or len(code)<1:
        resp['code'] = -1
        resp['msg'] = '需要code'

        return jsonify(resp)
    return jsonify(resp)

转载请注明:虚坏叔叔 » Python flask实战订餐系统微信小程序-31定义后端接口接收小程序请求

喜欢 (27)

您必须 登录 才能发表评论!