def post(self): data = UserRegister.parser.parse_args() #to use the parser if UserModel.find_by_username(data['username']): #same as if User.find_by_username(data['username']) is not None return {"message": "A user with that name already exists"}, 400 #400 is bad http RC user = UserModel(**data) #**data is same as data['user'], data['password']..parameter unpacking.. user.save_to_db() # connection = sqlite3.connect('data.db') # cursor = connection.cursor() # # query = "INSERT INTO users VALUES(NULL, ?, ?)" #user id is auto incremented. hence null. # cursor.execute(query, (data['username'], data['password'])) # # connection.commit() # connection.close() return {"message": "User created successfully."}, 201
def post(self): data = UserRegister.parser.parse_args() if UserModel.find_by_username(data['username']): return {"message": "User with that username already exists."}, 400 user = UserModel(data['username'],data['password']) user.save_to_db() #connection = sqlite3.connect('data.db') #cursor = connection.cursor() # #query = "INSERT INTO {table} VALUES (NULL, ?, ?)".format(table=self.TABLE_NAME) #cursor.execute(query, (data['username'], data['password'])) # #connection.commit() #connection.close() return {"message": "User created successfully."}, 201
def setUp(self): super(ItemTest, self).setUp() with self.app() as client: with self.app_context(): UserModel('test_user', 1234).save_to_db() auth_request = client.post( '/auth', data=json.dumps({ 'username': '******', 'password': '******' }), headers={'Content-Type': 'application/json'}) # our JWT token, need to include in authorization header auth_token = json.loads(auth_request.data)['access_token'] # must be in this format #header = {'Authorization': 'JWT ' + auth_token} # or use format string self.access_token = f'JWT {auth_token}'
def post(cls): data = cls.parser.parse_args() if (UserModel.find_by_email(data['email'])): return {'message': 'This email has already registed.'}, 500 try: user = UserModel(**data) user.save_to_db() except Exception as e: return {'message': 'Register cannot be done.'}, 500 user_id = UserModel.find_by_email(data['email']).user_id email = Email(user_id, data['email']) checked = email.send_confirm_email() if (not checked): return {'message': 'Email server has problems.'}, 500 return {'message': 'Rigster is suceed, please check your email.'}, 200
def post(self): data = UserRegister.parser.parse_args() if UserModel.find_by_username(data["username"]): return {"message": "A user with that username already exists"} # connection = sqlite3.connect("data.db") # cursor = connection.cursor() # query = "INSERT INTO users VALUES (NULL, ?, ?)" # cursor.execute(query, (data["username"], data["password"])) # connection.commit() # connection.close() user = UserModel(**data) user.save_to_db() return {"message": "User created successfully"}, 201
def post(self): data = UserRegister.parser.parse_args() if UserModel.find_by_username(data["username"]): return { "message": "username already exist, please try another one." }, 400 try: user = UserModel( **data ) #unpack data to data["username"] and "password") we can do this cause we are using parser #and we know we will always only have those 2. except: return {"message": "An error occured registering the user"}, 500 user.save_to_db() return {"message": "User created suscessfully."}, 201
def post(self): data = UserRegister.parser.parse_args() user = UserModel.find_by_username(data['username']) if user: return {"Message": "The user has already been registered"}, 400 # connection = sqlite3.connect('data.db') # cursor = connection.cursor() # query = "INSERT INTO users VALUES (NULL, ?, ?)" # cursor.execute(query, (data['username'], data['password'])) # connection.commit() # connection.close() #user = UserModel(None, data['username'], data['password']) user = UserModel(None, **data) user.save_to_db() return {"Message": "User created successfully."}, 201
def test_crud(self): with self.app_context(): user = UserModel('test', 'abcd') self.assertIsNone( UserModel.find_by_username('test'), "Found an user with name 'test' before save_to_db") self.assertIsNone(UserModel.find_by_id(1), "Found an user with id '1' before save_to_db") user.save_to_db() self.assertIsNotNone( UserModel.find_by_username('test'), "Did not find an user with name 'test' after save_to_db") self.assertIsNotNone( UserModel.find_by_id(1), "Did not find an user with id '1' after save_to_db")
def put(cls, user_id: int): data = _edit_parser.parse_args() user = UserModel.find_by_id(user_id) userJSON = user.json() data['email'] = userJSON['email'] data['hashedPassword'] = userJSON['hashedPassword'] data['profile_pic'] = userJSON['profile_pic'] updated_user = UserModel(**data) user.first_name = data['first_name'] user.last_name = data['last_name'] user.username = data['username'] user.location = data['location'] user.bio = data['bio'] user.save_to_db() return updated_user.json(), 200
def setUp(self): # need to call BaseTest setUp method because setUP of ItemTest # is overriding it # call setup method of SUPER class, way in python # get super class super(ItemTest, self) and "." call method on it super(ItemTest, self).setUp() with self.app() as client: with self.app_context(): UserModel('test', '1234').save_to_db() auth_request = client.post( '/auth', data=json.dumps({ 'username': '******', 'password': '******' }), headers={'Content-Type': 'application/json'}) auth_token = json.loads(auth_request.data)['access_token'] self.access_token = f'JWT {auth_token}'
def post(self): data = UserRegister.parser.parse_args() print(data) validate = UserModel.validity_check(data["username"], data["number"]) if "username" in validate or "number" in validate: return {"msg" : "invalid registration detail/s", "details" : validate} try: print("about to instantiate") user = UserModel(**data) print("about to change the date format") user.birth = datetime.strptime(data['birth'], '%Y-%m-%d').date() print("about to save") print(user) user.save_to_db() return {"msg" : "User Successfully created"} except: return {"msg" : "Something went wrong"}, 500
def post(self): data = UserRegister.parser.parse_args() if UserModel.find_by_username(data['username']) is not None: return {'Status': 400, 'Message': 'User Already Exists'}, 400 new_user = UserModel(data['username'], data['password']) try: new_user.save_to_db() return { 'Status': 201, 'Message': 'User Create Successfully', 'New User': new_user.username }, 201 except: return { 'Status': 500, 'Message': 'Error: Failed to insert into the database.' }, 500 return {'Status': 201, 'Message': 'User Create Successfully'}, 201
def post(self): data = UserRegister._user_parser.parse_args() if UserModel.find_by_username(data['username']): return {"message": "A user with that name already exists."}, 400 elif UserModel.find_by_email(data['email']): return {"message": "That email is in use."}, 400 random_data = randomData() # print(random_data) _id = hashData(str(random_data)) # print(_id) user = UserModel(_id, **data) user.save_to_db() return {"message": "User created successfully."}, 201
def post(self): data=UserRegister.parser.parse_args() if UserModel.find_by_username(data['username']) is not None: return {'message':'El usuario ya existe con ese nombre'},400 user= UserModel(**data) #esto el lo mismo que user=UserModel(data['username'],data['password']) #es decir, **data convierte los valores asociado a unaq key en una tuple #ed, pasa de data={'username':valor1,'password':valor2} # a (valor1,valor2) user.save_to_db() return {"message":"user created correctly"},201
def test_get_user(self): with self.app() as client: with self.app_context(): # Setup UserModel('test', '1234').save_to_db() # Exercise path = '/user/1' response = client.get(path) # Verify expected = { 'description': 'Request does not contain an access token.', 'error': 'authorization_required' } self.assertEqual(401, response.status_code) self.assertDictEqual(expected, json.loads(response.data))
def post(self): data = UserRegister.parser.parse_args() if UserModel.find_by_username(data['username']): return { "message": "A user with that username is already exits." }, 400 user = UserModel(data['username'], data['password']) try: user.save_to_db() except: return { "message": "An error occured inserting the user to the database." }, 500 return {"message": "User created successfully."}, 201
def post(self): json_data = request.get_json() if not json_data: return {'error': 'no input data provided!'}, 400 try: data = UserRegister.user_register_schema.load(json_data) except ValidationError as err: return err.messages, 422 if UserModel.find_by_username(data['username']): return { 'error': 'user {} already exists!'.format(data['username']) }, 400 user = UserModel(**data) user.save_to_db() return {"message": "User created successfully."}, 201
def put(self, id): name = request.json.get('name') email = request.json.get('email') address = request.json.get('address') cellphone = request.json.get('cellphone') user = UserModel.query.filter_by(id=id).first() if user is None: user = UserModel(id) else: user.name = name user.email = email user.address = address user.cellphone = cellphone db.session.add(user) db.session.commit() return {"message": "Change successfully!"}
def post(self): """ Process user register """ message = [] formData = self.parseBody(self.request.body) if self._validate(formData, message) == True: codeActivation = Helper.random_string() myUser = UserModel( email=str(formData['femail']), password=str(Helper.hash_password(formData['fpassword'])), groupid=3, status=UserModel.STATUS_INACTIVE, code_activation=codeActivation, date_activation=datetime.now()) try: myUser.put() except: self.responseJSON('DATA_CREATE_FAILED') return # send email activation mailTemplate = 'mail_templates/account_activate.html' with open(mailTemplate) as f: htmlBody = f.read() userActivationLink = self.getHostname( ) + '/api/user/activation?e=' + myUser.email + '&c=' + codeActivation messageBody = htmlBody.format(activation_url=userActivationLink) Helper.send_mail(messageBody, 'Welcome to Olli-AI', myUser.email) self.responseJSON( '', **{ 'message': 'User register success.', 'data': { 'id': myUser.key.id() } }) else: self.responseJSON('DATA_VALIDATE_FAILED', **{'data': message}) return
def post(self): data = _user_parser.parse_args() user = UserModel.find_by_username(data['username']) if user: return { "message": f"A user with the username {username} already exists" }, 400 user = UserModel(**data) try: user.save_user_to_db() except: return {"message": f"An error occurred! 😞"}, 500 return {"message": "User created successfully! 💃🏿"}, 201
def put(self, id: int): data = _user_parser.parse_args() user = UserModel.find_by_id(id) if user: user.username = data['username'] user.password = data['password'] user.email = data['email'] user.telefone = data['telefone'] user.cpf = data['cpf'] user.msg = data['msg'] user.promocao = data['promocao'] else: user = UserModel(id, **data) user.save_to_db() return (user.json(), {'message': 'Usuário alterado com Sucesso', 'st':'1'}), 201
def post(self): item = request.get_json() if request.get_json() else request.form try: if item: model = UserModel() model.first_name = item['first_name'] model.last_name = item['last_name'] model.email = item['email'] model.active = item['active'] if 'active' in item else True model.password = encrypt(item['password']) model.timestamp = date.today() model.save() return 'created', 201 else: return 'not created, invalid payload', 400 except Exception as e: return f"{e}", 500
def post(self): data = RegisterUser.parser.parse_args() if UserModel.find_user_by_username(data["username"]): return {"message": "username already exists"}, 400 ''' conn = sqlite3.connect('Database') cursor = conn.cursor() insert_user_query = "INSERT INTO users VALUES (NULL, ?, ?)" cursor.execute(insert_user_query, (data["username"], data["password"])) conn.commit() conn.close() ''' user = UserModel(**data) user.save_to_db() return {"message": "User created successfully"}, 201