def setUp(cls): cls.user = User(name="Test_User") cls.user.add_item(1, "Spectrum", "Vintage home computer system", Money(300.50)) cls.user.add_item(2, "Amiga", "Older computer", Money(50.49)) cls.user2 = User(name="Test_User2") cls.user2.add_item(1, "Spectrum", "Vintage home computer system", Money(300.50)) cls.user2.add_item(2, "Amiga", "Older computer", Money(50.49))
def get_user(self, article: WebElement): name, user_link = [None] * 2 try: name = article.find_element_by_css_selector('._5pb8.m_1djjlbjav._8o._8s.lfloat._ohe').get_attribute('title') user_link = self.parse_url( article.find_element_by_css_selector('._5pb8.m_1djjlbjav._8o._8s.lfloat._ohe').get_attribute('href')) b = article.find_element_by_css_selector('.igjjae4c.glosn74e.f2jdl7fy.cxfqmxzd').get_attribute("innerHTML") return User(user_link, name, b) except NoSuchElementException: return User(user_link, name)
def register(): if request.method == "POST": #POST METHOD username = request.form["username"] password = request.form["password"] confirm_password = request.form["confirm_password"] account_type = request.form["account_type"] if password != confirm_password: flash("The two password don't match!") return render_template("user/register.html") try: if userService.getOneByUsername(username): flash("There is already one account with this username!") return render_template("user/register.html") except: from domain.user import User from controller import db user = User(username, password, "", account_type) db.session.add(user) db.session.commit() flash("Account registered successfully!") return redirect(url_for("auth.login")) else: #GET Method: return render_template("user/register.html")
def get_user(article: WebElement) -> User: name, user_url = [None] * 2 user_class = '._5pb8.m_1djjlbjav._8o._8s.lfloat._ohe' badge_class = '.igjjae4c.glosn74e.f2jdl7fy.cxfqmxzd' try: name = article.find_element_by_css_selector( user_class).get_attribute('title') user_url = Crawler.parse_user_url( article.find_element_by_css_selector(user_class).get_attribute( 'href')) badge = article.find_element_by_css_selector( badge_class).get_attribute("innerHTML") return User(user_url, name, badge) except NoSuchElementException: return User(user_url, name)
def list_all(uid): """ List data from the specified user """ user = User.get(uid) data = UserDataService(user).find_all_folders() return jsonify(data)
def sync_users(): """ Create a new index if a new filesystem is found and sync it. Delete the index if the filesystem has been removed. """ home_path = app.config['USER_HOME_PATH'] temp_path = app.config['USER_TEMP_PATH'] users = [(o, False) for o in os.listdir(home_path) if ( os.path.isdir(home_path + '/' + o) and not os.path.islink(home_path + '/' + o))] users += [(o, True) for o in os.listdir(temp_path) if ( os.path.isdir(temp_path + '/' + o) and not os.path.islink(temp_path + '/' + o))] new_users = set(users) - set(User.users.keys()) deleted_users = set(User.users.keys()) - set(users) for user in new_users: user_obj = User(user[0], anonymous=user[1]) service = UserDataService(user_obj) service.build_index() app.logger.info(u"Added user: {u}. Is anonymous: {isAno}" .format(u=user[0], isAno=user[1])) for user in deleted_users: service = UserDataService(User.get(user[0])) service.destroy_index() del User.users[user[0]] app.logger.info(u"Deleted user: {u}.".format(u=user[0]))
def put(event, context): try: id = event['pathParameters']['id'] data = json.loads(event['body']) # create new user object with extended attributes email = data.get("email") age = data.get("age") name = data.get("name") liking = data.get("liking") mobile = data.get("mobile") gender = data.get("gender") user = User(id, name, email, mobile, age, gender, liking) # update user in datastore by id response = updateUser(user) return { "statusCode": 200, "body": json.dumps("user successfull updated") } except Exception as e: return { "statusCode": 500, "body": json.dumps("error in processing request") }
def parse_users(user_names): conn = DB_Connector("weplay") res = [] for user_name in user_names: user_id = conn.find_user_id(user_name) res.append(User(user_id)) conn.close() return res
def sync_all_users(): """ Static method for syncing all folders and files for all users """ users = User.get_users() for user in users: try: TaskService(full_sync_process, user=user) except ValueError, error: current_app.logger.error(error)
def user_saved_tracks(username, token): spotify = spotipy.Spotify(auth=token) search = spotify.current_user_saved_tracks() conn = DB_Connector("weplay") user_id = conn.find_user_id(username) user = User(user_id) user = User(user_id) # user_authors = set() # user_genres = set() # user_tracks = [] for item in search['items']: track_data = item['track'] track_genres = [] track_authors = [] for artist_data in track_data['artists']: track_authors.append(Artist(artist_data['id'], artist_data['name'])) user.add_author(Artist(artist_data['id'], artist_data['name'])) track_params_data = spotify.audio_features([track_data['id']])[0] track_params = Params(track_params_data['danceability'], track_params_data['energy'], track_params_data['instrumentalness'], track_params_data['valence']) user.add_track( Track(track_data['id'], track_data['name'], track_authors, track_genres, params=track_params)) conn.put_user(user) conn.close()
def destroy(uid): user = User.get(uid) if user: zfs_service = ZFSService(uid) data = zfs_service.destroy(user) if data is not True: abort(500, data['error']) return jsonify(data) abort(404, USER_ERROR_MSG.format(u=uid))
def returnOne(self, username, password): user = Query() element = self.table.search(user.username == username and user.password == password) if element: return User(**element[0]) return None
def __parse__(self): self.user = User() try: raw_user = utilities.crypto.decode_jwt_token(token=self.token) self.user.id = raw_user['id'] self.user.username = raw_user['username'] self.user.role = raw_user['role'] except Exception as e: self.exception = e
def setUp(self): self.auction = Auction( creator=User("test_user"), items=[ Item(1, "test_item", "test", Money(12.0)), Item(1, "test_item", "test", Money(12.0)), ], ) self.repository = FakeAuctionRepository() self.repository.add(self.auction)
def destroy_idx(uid): """ Destroy index for the specified user. """ warnings.warn(("This function shouldn't be used, instead this application " "should automatically find the deleted filesystem and " "destroy its index."), DeprecationWarning) user = User.get(uid) if user: return jsonify(EsService().destroy_index(user.uid)) abort(404, USER_ERROR_MSG.format(u=uid))
def login(): credentials = request.get_json() print(credentials) user_repo = Utils.user_repo user = User(**credentials) if user_repo.returnOne(user.username, user.password): return { 'token' : createToken(credentials)} else: raise InvalidUsage('Username or Password incorrect', status_code=410)
def __handle_deleted_event(self, folder): """ Destroys the index by finding the name of the deleted filesystem :param folder: :return: """ username, isAnonymous = self.__handle_event(folder) with self.app.app_context(): user = User.get(username) user_service = UserDataService(user) user_service.destroy_index() del User.users[username]
def create(uid): """ Create new index for the specified user. :param uid: """ warnings.warn(("This function shouldn't be used, instead this application " "should automatically find the new filesystem and create " "the index for it."), DeprecationWarning) user = User.get(uid) if user: return jsonify(EsService().create_index(user.uid, overwrite=True)) abort(404, USER_ERROR_MSG.format(u=uid))
def __create_user__(self): try: raw_data = json.loads(self.data) user = User(email=raw_data['email'], password=raw_data['password']) user.create() result = self.user_service.create_user(user=user) if result is None: raise HttpCreated(data=ResponseData(ex=None, data={ 'id': user.id, 'email': user.email })) elif isinstance(result, EmailExisted): raise HttpFound(data=ResponseData(ex=result, data=None)) else: raise HttpInternalError( data=ResponseData(ex=result, data=None)) except Exception as e: Logger.exception(e) raise HttpBadRequest(data=ResponseData(ex=e, data=None))
def sync_folder(uid, node_id): """ Sync the folder by comparing datastructures on both the filesystem and the ES DB. """ user = User.get(uid) if user: try: TS(folder_sync_process, user=user, node_id=node_id) except ValueError, error: app.logger.error(error) return jsonify(dict(error='job is already running')), 200 data = dict(status='job created') return jsonify(data), 201
def __scan_user__(raw_data): user = User.scan({ 'id': raw_data[0], 'email': raw_data[1], 'password': raw_data[2], 'github': { 'token': raw_data[3], }, 'audit': { 'created_at': raw_data[4], 'last_access': raw_data[5], }, }) return user
def sync_uid(uid): """ Sync the filesystem and ES DB by scanning and comparing datastructures on both the filesystem and ES DB. """ user = User.get(uid) if user: try: TS(full_sync_process, user=user) except ValueError, error: app.logger.error(error) return jsonify(dict(error='job is already running')), 200 data = dict(status='job created') return jsonify(data), 201
def build(uid): """ Build new index for the specified user, build folders first and then later fill it with files. This function is heavy, so it executes asynchronously. """ user = User.get(uid) if user: try: TS(build_process, user=user) except ValueError, error: app.logger.error(error) return jsonify(dict(error='job is already running')), 200 data = dict(status='job created') return jsonify(data), 201
def find_username(self, user: str) -> User: cursor = self.database_connector.cursor() query = "SELECT * FROM Users WHERE username LIKE %s" cursor.execute(query, (user, )) user = None for (id, username, email, hashedPassword) in cursor: user = User() user.user_id = id user.username = username user.email = email user.hashed_password = hashedPassword cursor.close() return user
def update_user_and_get(self, github_token, flask_global): request_user = User() request_user.access_token = github_token flask_global.user = request_user github_user = self.github.get('/user') github_id = github_user['id'] user = User.query.filter_by(github_id=github_id).first() if user is None: user = User() user.github_id = github_id user.login = github_user['login'] self.db_session.add(user) user.access_token = github_token self.db_session.commit() return user
def registration(self, form: RegistrationForm): # регистрация user = User() user.login = form.login.data user.email = form.email.data user.password = form.password.data user.role_id = 2 repeat_password = form.password_again.data if user.password == repeat_password: user.password = generate_password_hash(user.password) try: self.user_resource.post(user) return "" except Exception: return "Такой пользователь уже есть в базе данных" else: return "Пароли не совпадают"
def signup(self, username: str, email: str, password: str) -> str: is_username_free = self.user_repository.is_username_free(username) if not is_username_free: raise ConflictSignup("username already exist") is_email_free = self.user_repository.is_email_free(email) if not is_email_free: raise ConflictSignup("email is already in use") hashed_password = self.password_hasher.generate_password_hash(password) user = User() user.username = username user.email = email user.hashed_password = hashed_password user.user_id = self.user_repository.save_new(user) token = self.jwt_service.create_token(user.username, user.email, user.user_id) return token
def check_request_user(req, method, user_id=None): # проверяет запрос для пользователей if not req: return jsonify({"error": "Empty request"}) elif not all(key in req for key in ["login", "password", "email", "role_id"]): return jsonify({"error": "Bad request"}) else: user = User() user.login = req["login"] user.password = generate_password_hash(req["password"]) user.email = req["email"] user.role_id = req["role_id"] if method == "post": return jsonify(user_resource.post(user)) elif method == "put": return jsonify(user_resource.put(user_id, user))
def get(self): try: param = str(self.request.get('term')).strip() except UnicodeEncodeError: return if param == "": return query = 'given_name: ' + param.lower() + ' OR surname: ' + param.lower() query_options = search.QueryOptions(limit=7) try: query_obj = search.Query(query_string=query, options=query_options) except QueryError: return results = search.Index(name=INDEX_NAME).search(query=query_obj) top7_names = [] for desired in results: found = User.query(User.id == desired.fields[0].value).get() if found is None: pass else: top7_names.append(found.given_name + ' ' + found.surname) top7_names.sort(key=lambda v: v.lower()) top7 = [] for desired in top7_names: elem = { 'id': desired, 'label': desired, 'value': desired } top7.append(elem) self.response.headers['Content-Type'] = 'application/json' result = json.dumps(top7) self.response.write(result)
def create(event, context): if 'userName' not in event: logging.error( "userName attribute does not exist. Validation Failed for request {}" .format(event)) raise Exception("Couldn't create the user.") name = event.get("userName") request = event.get("request") userAttributes = request.get("userAttributes") id = userAttributes.get("sub") phone_number = userAttributes.get("phone_number") email = userAttributes.get("email") user = User(id, name, email, phone_number) user.id = id user.email = email user.name = name user.mobile = phone_number return addUser(user)
def setUpClass(cls): cls.user = User(name="Test-user") cls.user.add_item(1, "Spectrum", "Vintage home computer system", Money(300.50)) cls.user.add_item(2, "Amiga", "Older computer", Money(50.49)) cls.repository = FakeUserRepository()
def do_the_register(): name = request.form.get('name') passwd = request.form.get('passwd') g.db.add(User(name=name, passwd=passwd)) g.db.commit()
def mock_user(): return User(id="1",first_name="a",last_name="b")
def login(self, event=NONE): user = User(self.username.get(), self.language.get()) self.changed_screen = True self.next_screen = Chat(user, self.window) self.grid_forget()
from werkzeug.security import generate_password_hash from domain import db_session from domain.user import User db_session.global_init("../db/system.db") session = db_session.create_session() users = [User(login="******", password=generate_password_hash("admin1"), role_id=1, email="*****@*****.**"), User(login="******", password=generate_password_hash("admin2"), role_id=1, email="*****@*****.**")] session.add_all(users) session.commit()
def add_user_command_handlers(command: commands.AddUser, user_repo): UserService(user_repo).create_user( User(id=cuid.cuid(), first_name=command.first_name, last_name=command.last_name))
db = sqlite3.connect(db_url) db.row_factory = sqlite3.Row return db def get_sesion(url=sqlalchemy_db): # 初始化数据库连接: engine = create_engine(url) # 创建DBSession类型: return sessionmaker(bind=engine)() # test db if __name__ == '__main__': # init_db,!!!!! delete the old one and create the new one init_db() print('create db: ok') # test sqlalchemy sess = get_sesion() sess.add(User(id=1, name='Test', passwd='Test')) sess.commit() print('test insert user(name=Test, passwd=Test): ok') user = sess.query(User).one() print('test reading user from the database: ') print('user: '******'print message of the user: '******'name: ', user.name, ', passwd', user.passwd) sess.close() print('The database works well.')
def json_to_user(self, json): from domain.user import User return json if json is None else \ User(json['id'], json['name'], json['email'], None, json['role'], json['seniorityLevel'], json['departmentId'])
def users(): ''' return all users that are registered ''' return jsonify(User.get_users_as_dict())
def setUpClass(cls): cls.user = User("test_user")
def list_user_musics(session, user_id: int, user_repo) -> List[Music]: user = user_repo.get_one(session, dict(id=user_id)) user_dto = User.from_orm(user) return user_dto.musics
from domain.recipe import Recipe from domain.user import User from utilities.utilities import Utils Utils.create() recipe_repo = Utils.recipe_repo user_repo = Utils.user_repo recipe_repo.clear() images = ["1610112777026.jpeg", "1610112823546.jpeg", "1610112797294.jpeg"] for i in range(3): recipe = Recipe(i.__str__(), "Name" + (i + 1).__str__(), "10", "easy", images[i], 46.56862409846464, 26.892768939521332) recipe.username = "******" recipe_repo.addRecipe(recipe) user_repo.addUser(User("a", "a")) user_repo.addUser(User("b", "b"))
def list_all(): """list all devices""" data = UserDataService(User.get('olav')).find_all() return jsonify(data)