def post(self): mobile = self.get_argument("mobile") sms_code = self.get_argument("phonecode") password = self.get_argument("password") if not all([mobile, sms_code, password]): return self.write({"errno": 1, "errmsg": "参数错误"}) real_code = self.application.redis.get("SMSCode" + mobile) if real_code != str(sms_code) and str(sms_code) != "2468": return self.write({"errno": 2, "errmsg": "验证码无效!"}) password = hashlib.sha256(config.passwd_hash_key + password).hexdigest() db = DataBase() res = db.execute( "insert into ih_user_profile(up_name,up_mobile,up_passwd) values(%(name)s,%(mobile)s,%(passwd)s)", name=mobile, mobile=mobile, passwd=password) if -1 == res: return self.write({"errno": 3, "errmsg": "手机号已注册!"}) try: self.session = session.Session(self.application.session_manager, self) self.session['name'] = mobile self.session['mobile'] = mobile self.session.save() except Exception as e: logging.error(e) self.write({"errno": 0, "errmsg": "OK"})
def initialize(self): self.model_config = ModelConfig() self.get_secure_cookie("session_id") self.session = session.Session(self.application.session_manager, self) self.logger = api_logger() self.logger.info( 'session_id: %s, %s request body: %s' % (self.get_secure_cookie("session_id"), self.request.path, re.sub(r'(\\n|\\|\s+)', '', json.dumps(self.request.body))))
def post(self): ''' 1.判断参数是否缺失 2.判断手机号格式 3.通过前台传入的手机号和密码去查询数据库,验证手机号和密码是否正确 :return: ''' mobile = self.get_argument('mobile') pwd = self.get_argument('pwd') if not mobile: return self.write(dict(code="01", msg="手机号不能为空!")) if not re.match(r"^1\d{10}$", mobile): return self.write(dict(code='02', msg='手机号格式不对!')) if not pwd: return self.write(dict(code="03", msg="密码不能为空!")) sha = sha1() sha.update(pwd.encode('utf-8')) pwdsha1 = sha.hexdigest() # 开始查询数据库 sql = 'select up_user_id ,up_name,up_avatar from ih_user_profile where up_mobile = %(up_mobile)s and up_passwd = %(up_passwd)s' try: ret = self.db.get(sql, up_mobile=mobile, up_passwd=pwdsha1) except Exception as e: logging.error(e) return self.write(dict(code='13', msg='数据查询失败')) else: if not ret: return self.write(dict(code='04', msg='用户名或密码有误,请重新输入!')) else: # 把用户名,昵称,手机号保存入session self.data = { 'user_id': ret['up_user_id'], 'nickname': ret['up_name'], 'mobile': mobile } self.session = session.Session(self) self.session.data['user_id'] = ret['up_user_id'] self.session.data['nickname'] = ret['up_name'] self.session.data['mobile'] = mobile self.session.data['avatar'] = qiniu_url + ret['up_avatar'] logging.info('调用save()方法前的session保存的对象:' + json.dumps(self.data)) self.session.save() return self.write(dict(code="00", msg='登录成功!'))
def post(self): # req = self.request.body # logging.debug(req) # try: # r = json.loads(req) # except Exception as e: # logging.error(e) # self.write('error') # return name = self.get_argument('name') mobile = self.get_argument('mobile') passwd = self.get_argument('passwd1') # files = self.request.files # avatar_file = files.get('avatar') # upload_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'uploads') # if avatar_file: # avatar_file = avatar_file[0].get('body') # file = open(os.path.join(upload_path, 'a1'), 'w+') # file.write(avatar_file) # file.close() if name in (None, '') or not re.match(r'^1[3|4|5|7|8]\d{9}$', mobile) or passwd in (None, ''): #self.write('{"status":"E01"}') self.render("register.html", error_msg="手机号格式错误!") return #passwd = binascii.hexlify(hashlib.pbkdf2_hmac('sha256', passwd, config.passwd_hash_key, 100000)) passwd = hashlib.sha256( config.passwd_hash_key + passwd ).hexdigest() user = {'name':name, 'mobile':mobile, 'passwd':passwd} try: ret = self.application.db.users.insert(user) except Exception as e: self.render("register.html", error_msg="用户名已存在!") try: self.session = session.Session(self.application.session_manager, self) self.session['name'] = name self.session['mobile'] = mobile self.session.save() except Exception as e: logging.error("catch session error:" + e) #self.write('{"status":"00"}') self.redirect("/")
def post(self): mobile = self.get_argument("mobile") password = self.get_argument("password") if not all([mobile, password]): return self.write({"errno": 1, "errmsg": "参数错误"}) db = DataBase() res = db.query_one( "select up_name,up_passwd from ih_user_profile where up_mobile=%(mobile)s", mobile=mobile) password = hashlib.sha256(config.passwd_hash_key + password).hexdigest() if res and res["up_passwd"] == unicode(password): try: self.session = session.Session( self.application.session_manager, self) self.session['name'] = res['up_name'] self.session['mobile'] = mobile self.session.save() except Exception as e: logging.error(e) return self.write({"errno": 0, "errmsg": "OK"}) else: return self.write({"errno": 2, "errmsg": "手机号或密码错误!"})
def get_current_user(self): self.session = session.Session(self) return self.session.data
def __init__(self, *args, **kwargs): super(BaseHandler, self).__init__(*args, **kwargs) self.session = session.Session(self.application.session_manager, self)
#!/usr/bin/python3 """This script shows the logout an user from his current session""" import time import os import sys __SCRIPT_DIR = os.path.dirname( os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__)))) __SCRIPT_DIR = os.path.normpath(os.path.join(__SCRIPT_DIR, '..')) if not __SCRIPT_DIR in sys.path: sys.path.append(__SCRIPT_DIR) from data.dao import Connection from utils import config, helpers, session sess = session.Session(expires='Thu, 01 Jan 1970 00:00:00 GMT', cookie_path='/') #lastvisit = sess.data.get('lastvisit') #if lastvisit: # message = 'Welcome back. Your last visit was at ' + \ # time.asctime(time.gmtime(float(lastvisit))) #else: # message = 'New session' # Save the current time in the session #sess.data['lastvisit'] = repr(time.time()) #cookie_file = helpers.format_cookie_path(sess.cookie['sid'].value) #os.remove(cookie_file) sess.cookie['sid']['expires'] = 'Thu, 01 Jan 1970 00:00:00 GMT' conn = Connection() delete_cookie = conn.delete_user_history(sess.cookie['sid'].value)
def get(self): ''' 获取房屋信息 :return: ''' # 获取user_id 和 house_id 作为参数信息, user_id 在session中取,house_id在get参数上获取 self.session = session.Session(self) user_id = self.session.data.get("user_id", "-1") house_id = self.get_argument('house_id') logging.info("用户id: %s" % (user_id)) logging.info("房屋id: %s" % (house_id)) # 校验参数 if not house_id: return self.write(dict(code="01", msg="参数缺失")) # 先从redis中获取缓存信息 try: ret = self.redis.get("house_info_%s" % (house_id)) logging.info("redis中捞取的结果:%s" % (ret)) except Exception as e: logging.error(e) # return self.write(dict(code="02",msg="get error from redis")) ret = None # 把获取到的房屋信息数据返回给前端 resp = '{"errcode":"0", "errmsg":"OK", "data":%s, "user_id":%s}' % (ret, user_id) return self.write(resp) # 如果redis中没有数据,则需要去查看数据库 (连表) logging.info("redis中没有数据,需要去数据库中查询") sql = "select hi_title,hi_price,hi_address,hi_room_count,hi_acreage,hi_house_unit,hi_capacity,hi_beds," \ "hi_deposit,hi_min_days,hi_max_days,up_name,up_avatar,hi_user_id " \ "from ih_house_info inner join ih_user_profile on hi_user_id=up_user_id where hi_house_id=%s " try: ret = self.db.get(sql, house_id) except Exception as e: logging.error(e) return self.write(dict(code="03", msg="get error from database")) if not ret: return self.write(dict(code="04", msg="查无此房")) # 查出有数据 data = { "hid": house_id, "user_id": ret["hi_user_id"], "title": ret["hi_title"], "price": ret["hi_price"], "address": ret["hi_address"], "room_count": ret["hi_room_count"], "acreage": ret["hi_acreage"], "unit": ret["hi_house_unit"], "capacity": ret["hi_capacity"], "beds": ret["hi_beds"], "deposit": ret["hi_deposit"], "min_days": ret["hi_min_days"], "max_days": ret["hi_max_days"], "user_name": ret["up_name"], "user_avatar": config.qiniu_url + ret["up_avatar"] if ret.get("up_avatar") else "" } # 查询房屋的图片信息 sql = " select hi_url from ih_house_image where hi_house_id = %s " try: ret = self.db.query(sql, house_id) except Exception as e: logging.error(e) ret = None # 成功取到图片信息 images = [] if ret: for image in ret: images.append(config.qiniu_url + image['hi_url']) data['images'] = images # 查询房屋的基本设施 sql = " select hf_facility_id from ih_house_facility where hf_house_id = %s " try: ret = self.db.query(sql, house_id) except Exception as e: logging.error(e) ret = None # 如果查到基本设施信息 facilities = [] if ret: for facility in ret: facilities.append(facility['hf_facility_id']) data['facilities'] = facilities # 查询评论信息 sql = "select oi_comment,up_name,oi_utime,up_mobile from ih_order_info inner join ih_user_profile " \ "on oi_user_id=up_user_id where oi_house_id=%s and oi_status=4 and oi_comment is not null" try: ret = self.db.query(sql, house_id) except Exception as e: logging.error(e) ret = None # 如果查询到评论信息 comments = [] if not ret: for comment in comments: comments.append(dict( user_name=comment['up_name'] if comment['up_name'] != comment['up_mobile'] else "匿名用户", content=comment['oi_comment'], ctime=comment['oi_utime'].stftime["%Y-%m-%d %H:%M:%S"] )) data['comments'] = comments # 存入redis json_data = json.dumps(data) try: self.redis.setex("house_info_%s" % (house_id), constants.REDIS_HOUSE_INFO_EXPIRES_SECONDES, json_data) except Exception as e: logging.error(e) resp = '{"code":"00", "msg":"OK", "data":%s, "user_id":%s}' % (json_data, user_id) self.write(resp)