如何验证客户是否登录
登录---产生sessionid----存到redis(服务端)-----返回给客户(客户端)
客户用sessionid去调用别的操作接口
make_response方法可以set cookie
import flask,time,json from lib import tools server = flask.Flask(__name__) #把当前python文件做为一个服务 @server.route('/login') def login(): username = flask.request.values.get('username') pwd = flask.request.values.get('pwd') if username == 'Amy' and pwd == '123456': session_id = tools.my_md5(username + time.strftime('%Y%m%d%H%M%S')) key = 'syz_session:%s'%username tools.op_redis(key,session_id,3600) res = {'session_id':session_id,'error_code':0,'msg':'登录成功','login_time':time.strftime('%Y%m%d%H%M%S')}#给用户返回的信息 json_res = json.dumps(res,ensure_ascii=False)#返回结果转为json res = flask.make_response(json_res)#构造成返回结果的对象,set cookie,make_response方法可以set cookie res.set_cookie(key,session_id,600)#最后的数字是cookie的失效时间,cookie存在浏览器中 #为了方便取cookie将username改为key,res.set_cookie(username, session_id, 600) return res @server.route('/posts') def posts(): # session = flask.request.values.get('session') # print('all cookies',flask.request.cookies)#{'syz_session:dongrui': '89a4bea873ee223045fc72d332b8c481'} cookies = flask.request.cookies#获取所有的cookie username = '' session = ''#定义这两个变量是为了:在没有传cookie的时候用的 for key,value in cookies.items(): if key.startswith('syz_session'): username = key session = value #调用接口的时候用户传过来的session,从cookie里面取过来的 # print('user',username)#user syz_session:dongrui # print('session',session)#session 89a4bea873ee223045fc72d332b8c481 redis_session = tools.op_redis(username)#从redis里面获取到的cookie if redis_session == session:#判断传过来的session和redis里面的session是否一致 title = flask.request.values.get('title') content = flask.request.values.get('content') article_key = 'article:%s'%title #key都以article为标题 tools.op_redis(article_key,content)#把文章写入redis res ={'msg':'文章发表成功!','msg_code':0} else: res = {'msg':'用户未登录!','msg_code':2009} return json.dumps(res,ensure_ascii=False)
项目添加环境变量:
用命令行运行start.py会报错,脱离了pycharm的环境变量
BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
import sys,os # sys.path.insert(0,r'D:workspacepythonsyz-dongruiDay8_面向对象 ew_api') print(os.path.abspath(__file__))#取当前路径,D:/workspace/python/syz/Day/new_api/bin/start.py #直接__file__,路径分隔符不对 BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#上一级,上一级的目录,D:/workspace/python/syz/Day/new_api print(BASE_PATH)#new_api sys.path.insert(0,BASE_PATH)#获取到程序的主目录 #========报错:ImportError: No module named 'flask'================= from lib.interface import server from config.setting import SERVER_PORT server.run( host = '0.0.0.0', port=SERVER_PORT, debug=True )