一个验证登录的程序:python编写flask架构restful风格--2017年4月6日

一个验证登录的程序

摘抄自:极客学院-Python RESTful API开发工具介绍及应用   http://www.jikexueyuan.com/course/623.html

 

import base64
import time
import random

from flask import Flask,request

app = Flask(__name__)

users = {
    "magigo": ["123456"]
}

def gen_token(uid):
    token = base64.b64encode(':'.join([str(uid),str(random.random()),str(time.time()+7200)]))
    users[uid].append(token)
    return token

def verify_token(token):
#    print token
    _token = base64.b64decode(token)
#    print users.get(_token.split(':')[0])[-1]
    if not users.get(_token.split(':')[0])[-1] == token:
        return -1
    if float(_token.split(':')[-1]) >= time.time():
        return 1
    else:
        return 0


@app.route('/index', methods=['POST','GET'])
def hello_world():
    print request.headers
    return 'Hello World'

@app.route('/login',methods=['POST','GET'])
def login():
    uid, pw = base64.b64decode(request.headers['Authorization'].split(' ')[-1]).split(':')
    if users.get(uid)[0] == pw:
        return gen_token(uid)
    else:
        return 'error'

@app.route('/test',methods=['POST','GET'])
def test():
    token = request.args.get('token')
    if verify_token(token) == 1:
        return 'data'
    else:
        return 'error'

if __name__=='__main__':
    app.run(debug=True)
import requests

r = requests.get('http://127.0.0.1:5000/login',auth=('magigo','123456'))
print r.text 


token = 'bWFnaWdvOjAuOTMxODYzMDIyNjA0OjE0OTE0Nzk3ODkuMDc='
r = requests.get('http://127.0.0.1:5000/test',params={'token':token})
print r.text

 

posted on 2017-04-06 18:23  jingbostar  阅读(1315)  评论(0编辑  收藏  举报

导航