def test_user_creation(self): #Check if user with wrong email is created correctly self.assertRaises(Exception, User, '12345') user = User() self.assertIs(user.email, 'Unknown') another_user = User('*****@*****.**') self.assertIs(another_user.email, '*****@*****.**')
def register(): if request.json and request.method == 'POST': data = request.get_json() email = check_key('email', data) if data['username'] is None or data['password'] is None: abort(400) if User.query.filter_by(username=data['username']).first() is not None: abort(400) v1 = client.CoreV1Api() body = client.V1Namespace() body.kind = 'Namespace' body.metadata = dict(name=data['username'], lables={ 'name': data['username'] }) pretty = 'true' try: api_response = v1.create_namespace(body, pretty=pretty) print(api_response) except ApiException as e: print("Exception when calling CoreV1Api->create_namespace: %s\n" % e) return jsonify({'code': 500, 'msg': '用户已存在'}) user_data = User(username=data['username']) user_data.email = email user_data.hash_password(data['password']) db.session.add(user_data) db.session.commit() return jsonify({'code': 200, 'msg': '帐号注册成功'}) else: return jsonify({'code': 500, 'msg': '请求方式错误'})
def post(self): google_user = users.get_current_user() name = self.request.get('name') user = User(name=name, email=google_user.email(), user=google_user,key_name=google_user.email()) user.put() settings = Settings(user=user, key_name=google_user.email()) settings.put() self.chack_login()
def add_user(): c = json.loads(request.get_data()) u = User(c['username'], c['password']) if create_user(u): return Response(json.dumps(ok), content_type="application/json") return Response(json.dumps(bad_with_msg(' create user fail')), status=404, content_type="application/json")
def save_user(): page = 1 # 接收页码 if request.values.get('page'): page = int(request.values.get('page')) id = request.form.get('id') name = request.form.get('name') password = generate_password_hash(request.form.get('password')) type = request.form.get('type') phone = request.form.get('phone') wechat = request.form.get('wechat') if id: User.query.filter(User.user_id == id).update({ 'user_name': name, 'user_password': password, 'user_type': type, 'user_phone': phone, 'user_wechat': wechat }) commit() else: user = User(name, password, type, phone, wechat) add(user) users = User.query.paginate(page=page, per_page=10) return toJson(users)
def post(self): user_id = self.get_argument("user_id", None) user_name = self.get_argument("user_name", None) user_avatar = self.get_argument("user_avatar", None) if user_id == None: res = {} res["code"] = -1 res["errinfo"] = "参数错误" self.write(res) return None try: user = self.db.query(User).filter(User.user_id == user_id).first() if user == None: user = User(user_id=user_id, user_name=user_name, user_avatar=user_avatar) self.db.add(user) self.db.commit() except BaseException as e: msg = traceback.format_exc() print(msg) res = {} res["code"] = -1 res["errinfo"] = "参数错误" self.write(res) return None new_token = self.generate_token() self.set_token(new_token, user_id) res = {} res["code"] = 0 data = {} data["token"] = new_token res["data"] = data res["errinfo"] = "login success !" self.write(res)
def show_update_user(username): up = json.loads(request.get_data()) upser = User(up['username'], up['password']) if update_user(upser): return Response(json.dumps(ok), content_type="application/json") return Response(json.dumps(bad_with_msg('this user no exist')), status=404, content_type="application/json")
def register(): """ 用户注册 --- tags: - 用户相关接口 description: 用户注册接口,json格式 parameters: - name: body in: body required: true schema: id: 用户注册 required: - username - password - email - type properties: username: type: string description: 用户名. password: type: string description: 密码. email: type: string description: 邮箱. type: type: string enum: ['admin', 'normal',] description: 用户类型. responses: 201: description: 注册成功 example: {'code':1,'message':注册成功} 406: description: 注册有误,参数有误等 """ if session['type'] != 1: return {'code': -1, 'result': '需superAdmin用户才能添加用户'} username = request.json['username'] # email = request.json['email'] password = request.json['newPass'] password2 = request.json['newPass2'] type = request.json['type'] user = User.query.filter_by(username=username).first() if user is not None: return {'code': -1, 'result': '此用户名已被注册'} role = Role.query.filter_by(type=type).first() if role is None: return {'code': -1, 'result': '此用户类型未找到'} db.session.add(User(username=username, password=password, role_id=role.id)) db.session.commit() return jsonify({'code': 1, 'result': '注册成功'})
def create_user(self, first_name, last_name, username, password): user = User(first_name=first_name, last_name=last_name, username=username, password=password) session = self.conect.connect_database() session.add(user) session.commit() session.close()
def signup(): # Signup form should be handled by view controller. # This handler will accept post data, create a new user and confirm. username = request.form.get('username') password = request.form.get('password') password_verify = request.form.get('password_verify') response = User.create_user(username, password, password_verify) return response
def load_user_from_request(request): api_key = request.headers.get('Authorization') if api_key: api_key = api_key.replace('Basic ', '', 1) try: user = User.verify_auth_token(api_key) return user except TypeError: pass return None
def get_current_user(user=None): if not user: user = users.get_current_user() # while - url: .* login: required not necessary if user: user_cache = memcache.get("user-"+user.email()) if user_cache is None: user_cache = User.get_by_key_name(user.email()) if user_cache: memcache.add("user-"+user.email(), user_cache) return user_cache
def post(self): if is_reg: username = self.get_argument('username') email = self.get_argument('email') password = self.get_argument('password') re_password = self.get_argument('re_password') if re_password == password: #简单加密 password = get_password(password) User.create(username=username, email=email, password=password, reg_data=datetime.now()) self.redirect(self.get_login_url()) else: self.write( "<script>alert('两次输入的密码不一致');history.back();</script>") else: self.write("<script>alert('注册功能暂时不对外开放');history.back();</script>")
def userinfo(name): conn,flag=mysqlconn(); sql="select * from users where username='******'" %(name); cursor=conn.cursor(); cursor.execute(sql); alldata=cursor.fetchall(); user=None; for element in alldata: user=User(element[0],element[3],element[4],element[2],element[1]);#id,name,passwd,age,location mysqlclose(conn,flag); return user;# 返回user对象
def reg(): payload = request.json name = payload.get('name') if session.query(User).filter(User.name == name).first() is not None: abort(409) abort(Response("{} is exist!".format(name))) try: user = User() user.name = payload.get('name') user.password = bcrypt.hashpw(payload['password'].encode(), bcrypt.gensalt()) #对密码进行加密,存放到数据库当中 # user.spwd = base64.b64encode(payload['password'].encode()) except Exception as e: print('reg error:',e) # exc.HTTPBadRequest() session.add(user) try: session.commit() return jsonify(id=user.id, name=user.name, token=gen_token(user.id)) except: session.rollback() abort(500) abort(Response('reg failed'))
def addUserToEvent(name, email, event_id): user = getUserByEmail(email) rsvp = getRsvp(event_id, email) if user is None: newUser = User(email=email, name=name) db.session.add(newUser) db.session.commit() if rsvp is None: newRsvp = Rsvp(event_id=event_id, user_email=email) db.session.add(newRsvp) db.session.commit() mail.notifyAdmin(event_id, email)
def login(): # Login form should be handled by view controller. # This handler will accept post data and confirm if the user is authenticated. username = request.form.get('username') password = request.form.get('password') user = User.find_user(username) if user: auth = user.authenticate(password) if auth: return "Logged in." else: return "Username and password don't match." return "Username and password don't match."
def login(name, passwd): conn,flag=mysqlconn(); sql="select * from users where username='******' and password=%s" %(name,passwd); cursor=conn.cursor(); cursor.execute(sql); alldata=cursor.fetchall(); user=None; if len(alldata)==0: print "User or password wrong"; return None else: for element in alldata: user=User(element[0],element[3],element[4],element[2],element[1]); mysqlclose(conn,flag); return user;# 返回user对象
def log_in(): j = json.loads(request.get_data()) jr = User(j['username'], j['password']) t = find_user(jr.username) if t is None: return Response(json.dumps(bad_with_msg('this user no exist')), status=404, content_type="application/json") if t.username == jr.username and t.password == jr.password: response = make_response(json.dumps(ok)) response.set_cookie('todocookie', t.username) return response else: return Response(json.dumps(bad_with_msg('password error')), status=404, content_type="application/json")
def get_current_user(self): """用户验证 如果存在 cookie 则根据用户 cookie 获取用户信息并返回, 否则返回 None """ uid = self.get_secure_cookie("uid") if not uid: return None else: user = "" try: user = User.get(User.id == uid) except DoesNotExist: self.clear_cookie("uid") return user
def post(self): user_id = self.get_argument("user_id", None) if user_id == None: self.write_miss_argument() return None user = self.db.query(User).filter(User.user_qq_id == user_id).first() if user == None: user = User(user_qq_id=user_id) self.db.add(user) self.db.commit() new_token = self.generate_token() self.set_token(new_token, user_id) res = {} res["code"] = 0 res["token"] = new_token res["msg"] = "login success !" self.write(res)
def post(self, *args, **kwargs): username = self.get_argument('username', '') password = self.get_argument('password', '') #用户和名密码不可为空 if (not username) or (not password): self.write("<script>alert('用户名或者密码不能为空');history.back();</script>") else: try: t_user = User.get(username=username) if get_password(password) == t_user.password: self.set_secure_cookie('uid', str(t_user.id)) self.redirect(self.get_argument('next', '/')) else: self.write( "<script>alert('用户名或密码错误');history.back();</script>") except DoesNotExist: self.write( "<script>alert('您输入的用户名不存在');history.back();</script>")
def index(): if request.method == 'POST': # 取表单数据查询用户登陆权限 user_name = request.form.get('username') password = request.form.get('password') user = User.get(user_name) # 从用户数据中查找用户记录 if user is None: flash("用户名不存在") else: if user.verify_password(password): # 校验密码 login_user( user, remember=True, duration=timedelta(minutes=5)) # 创建用户 Session,超时为5分钟 return render_template('dashboard.html', user_name=user_name) else: flash("用户名或密码有误") return render_template('login.html') else: return render_template('login.html')
def test_adverts_creation(self): #Check if advert counter is working correctly first advert1 = Advert(None, None, None) advert2 = Advert(None, None, None) self.assertIs(advert1.id, 0) self.assertIs(advert2.id, 1) #Check owner of created adverts is assigned correctly to adverts user = User('*****@*****.**') advert3 = Advert(user, None, None) self.assertIs(advert3.owner, 'Unknown') advert4 = Advert(user.email, None, None) self.assertIs(advert4.owner, user.email) #Let's see what happens when we pass invalid prices and quantities advert5 = Advert(user.email, 'aaa', 'bbb') self.assertEquals(advert5.price, 0.0) self.assertEquals(advert5.quantity, 0) #Create a good one and see that everything is OK advert6 = Advert(user.email, 23.15, 2) self.assertIs(advert6.owner, user.email) self.assertEquals(advert6.price, 23.15) self.assertEquals(advert6.quantity, 2)
def register(name, passwd, age, location): """ :param name, passwd, age, location :param """ conn,flag=mysqlconn(); # 获取users表中最大的user_id,最大值加1作为新的user的id sql="select max(cast(user_id AS SIGNED)) from users"; cursor=conn.cursor(); cursor.execute(sql); alldata=cursor.fetchall(); max_id=alldata[0][0]; user_id=str(max_id+1); # 插入数据库 sql="insert into users (user_id, location, age, username, password) VALUES ('%s','%s','%s','%s','%s')" %(user_id,location,age,name,passwd); cursor.execute(sql); conn.commit(); user=None; user=User(user_id,name,passwd,age,location); mysqlclose(conn,flag); return user;# 返回user对象
def createUser(): if request.method == 'POST': try: ob = User(**request.json) data = User.query.filter_by(email=ob.email).first() if data: return jsonify({"error": "Sorry User Exists - 401"}) else: ob.uid = uuid.uuid4() ob.password = generate_password_hash(ob.password, method='sha256') ob.save() result = UserSchema().dump(ob) otpGenreationForUserMail(result.data['email']) return jsonify(result.data) except Exception as error: return jsonify({"error": str(error)}), 400
def test_password_setter(self): u = User(password='******') self.assertTrue(u.password_hash is not None)
return num else: print("输入有误,请重新输入!!!") # 输入账号与密码 def inputInfo(): return input("请输入账号和密码(逗号隔开):").split(',') if __name__ == '__main__': # 连接redis数据库 RedisUtil.connect() while True: # 初始化界面 num = index() # 输入账号密码 username, password = inputInfo() # 实例化一个用户类 user = User(username, password) if num == '1': urls.login(user) #登录 elif num == '2': urls.regist(user) # 注册 elif num == '3': urls.changePasswd(user) # 改密 elif num == '4': urls.deleteUser(user) # 注销 else: break
def newUser(self, userLabel, session): user = User(userLabel) session.add(user) return self.getObject(User, userLabel, session)
def view_user(id): # Returns user data (not the password) user = User.get_user_by_id(id) data = User.get_json(user) return json.dumps(data)
def test_no_password_getter(self): u = User(password='******') with self.assertRaises(AttributeError): u.password
def load_user(user_name): return User.get_by_id(user_name)
from flask import Flask, render_template, request, session, make_response, json from model.model import Book, User import csv import utils app = Flask(__name__) curr_user = User("", "", "", "", "") user_sim = {} @app.route('/') def index(): if (curr_user and curr_user.name): recommend_books = utils.recommend_books(user_sim, curr_user.id) print len(recommend_books) if len(recommend_books) == 0: recommend_books = utils.popular_books(12) else: recommend_books = utils.popular_books(12) return render_template('index.html', books=recommend_books) @app.route('/books/<bookid>/') def book_info(bookid): curr_book = utils.bookinfo(bookid) interested_books = utils.recommend_books(user_sim, curr_user.id) if not interested_books or len(interested_books) == 0: interested_books = utils.popular_books(10) return render_template('bookpage.html',