标签:python
Python RESTful API 开发
需要下载:flask
requests :http://docs.python-requests.org/zh_CN/latest/user/quickstart.html
首先,编写一个验证登陆的程序:
创建flask项目:
#!/usr/bin/env python # -*- coding: utf-8 -*- import base64 import random import time from flask import Flask, request app = Flask(__name__) users = { "XX": ["XXXXX"] # 这里,用户名和密码是电脑的登陆密码。 } 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): _token = base64.b64decode(token) 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(‘/‘, methods=[‘GET‘]) def index(): print request.headers return ‘hello‘ @app.route(‘/login‘, methods=[‘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(‘/test1‘, methods=[‘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)
编写:request_py:
#!/usr/bin/env python # -*- coding: utf-8 -*- import requests # r = requests.get(‘http://127.0.0.1:5000/login‘, auth=(‘zx‘, ‘thystar‘)) # print r.text # 先运行上面的代码获得token,然后将taken值复制,运行后面的代码 # 每次运行得到的token都不一样 token = ‘eng6MC42NTEwNDY2ODU2NzQ6MTQzNDczMzQwMi4zMQ==‘ r = requests.get(‘http://127.0.0.1:5000/test1‘, params={‘token‘: token}) print r.text
极客学院:http://www.jikexueyuan.com/course/1230.html
标签:python
原文地址:http://4440271.blog.51cto.com/4430271/1663736