def login(header: str) -> Dict: try: if 'Basic' in header: username, password = _decode_basic(header) with session_scope() as session: user = db_interface.query_user(username, session) if _verify_password(user.password_hash, password) and not user.token: db_interface.create_token(session, user) token = db_interface.query_token(user.token, session) return token.info() elif _verify_password(user.password_hash, password) and user.token: token = db_interface.query_token(user.token, session) if not token.is_valid(): token.refresh() return token.info() raise exc.AuthError('User already has a token assigned.') raise exc.AuthError('Invalid username or password.') elif 'Token' in header: token_str = _get_token(header) with session_scope() as session: token = db_interface.query_token(token_str, session) token.refresh() return token.info() raise exc.AuthError('Invalid authentication method.') except (exc.SessionError, exc.AuthError) as e: raise e
def lock_resources(self, key, resources, lock_type=LockType.EXCLUSIVE, greedy=False, clean_shared_locks=False): # sort resources by type sorted_resources = self.sort_resources_by_type(resources) # create an overall result that will be the aggregate of the results for # each resource batch result = LockResult(greedy) with session_scope() as session: for rtype in sorted_resources: model = self.get_resource_model(rtype) # convert the set to a list sorted_resources[rtype] = list(set(sorted_resources[rtype])) # check range resources conflict self._check_item_list_conflicts(model, sorted_resources[rtype]) #----------------------------------------------------------- # set up varaibles to control batch processing loop #----------------------------------------------------------- total = len(sorted_resources[rtype]) batch_size = model.BATCH_PROCESS_SIZE # set to the size the model supports start = 0 #----------------------------------------------------------- # Loop until all batches have been processed #----------------------------------------------------------- while start < total: # get the batch end = start + min(batch_size, total - start) batch = { item.uuid: item for item in sorted_resources[rtype][start:end] } #------------------------------------------------------- # Process the batch of resources #------------------------------------------------------- logger.info("process lock (type: {}) batch {}:{}".format( rtype, start + 1, end)) result += self.lock_items(session, key, model, batch, lock_type, greedy, clean_shared_locks) # update the start and end of the slice for the next iteration start += batch_size return result
def fetch_user(id: Optional[int] = None, name: Optional[str] = None): with session_scope() as session: query = session.query(User) if id: query = query.filter(User.id == id) if name: query = query.filter(User.name == name) return query.all()
def get(self, username): with session_scope() as session: try: user = db_interface.query_user(username, session) return marshal(user.info(), models.user_info), 200 except exc.SessionError as e: return marshal(e.message(), models.message), 404
async def create_thing(self, data): with database.session_scope() as session: thing, errors = create_thing_schema.load(data, session=session) session.add(thing) session.flush() data, errors = thing_schema.dump(thing) return data
def insert_todo(user_id: int, title: str, description: str, deadline: datetime) -> Todo: todo = Todo(user_id=user_id, title=title, description=description, deadline=deadline) with session_scope() as session: session.add(todo) session.flush() return todo
def put(self, user): try: data = request.get_json() if 'password' in data: data['password'] = auth.hash_password(data['password']) with session_scope() as session: db_interface.update_user(current_user, data) return 200 except exc.SessionError as e: return marshal(e.message(), models.message), 400
def logout(header: str) -> None: try: token_str = _get_token(header) with session_scope() as session: token = db_interface.query_token(token_str, session) db_interface.delete_token(token, session) pass except (exc.AuthError, exc.SessionError) as e: raise e
def _validate_token(token_string: str) -> bool: with session_scope() as session: try: token = db_interface.query_token(token_string, session) if token.is_valid(): return True else: db_interface.delete_token(token, session) return False except exc.SessionError as e: raise exc.AuthError(str(e))
def post(self): try: data = request.get_json() if data: data['password'] = auth.hash_password(data['password']) with session_scope() as session: db_interface.create_user(data, session) pass else: raise exc.SessionError('No JSON data provided') except exc.SessionError as e: return marshal(e.message(), models.message), 400
def unlock_resources(self, key, resources, greedy=False): result = LockResult(greedy) sorted_resources = self.sort_resources_by_type(resources) with session_scope() as session: for rtype in sorted_resources: model = self.get_resource_model(rtype) # convert the set to a list sorted_resources[rtype] = list(set(sorted_resources[rtype])) #----------------------------------------------------------- # set up varaibles to control batch processing loop #----------------------------------------------------------- total = len(sorted_resources[rtype]) batch_size = model.BATCH_PROCESS_SIZE # set to the size the model supports start = 0 #----------------------------------------------------------- # Loop until all batches have been processed #----------------------------------------------------------- while start < total: # get the batch end = start + min(batch_size, total - start) batch = { item.uuid: item for item in sorted_resources[rtype][start:end] } #------------------------------------------------------- # Process the batch of resources #------------------------------------------------------- logger.info("process unlock (type: {}) batch {}:{}".format( rtype, start + 1, end)) result = result + self.unlock_items( session, key, model, batch, greedy) # update the start and end of the slice for the next iteration start += batch_size return result
def fetch_todo(id: Optional[int] = None, user_id: Optional[int] = None, title: Optional[str] = None, description: Optional[str] = None, deadline: Optional[datetime] = None): with session_scope() as session: query = session.query(Todo) if id: query = query.filter(Todo.id == id) if user_id: query = query.filter(Todo.user_id == user_id) if title: query = query.filter(Todo.title == title) if description: query = query.filter(Todo.description == description) if deadline: query = query.filter(Todo.deadline == deadline) return query.all()
def transfer_resources(self, src_key, dest_key, resources): sorted_resources = self.sort_resources_by_type(resources) for rtype in sorted_resources: with session_scope() as session: model = self.get_resource_model(rtype) # convert the set to a list sorted_resources[rtype] = list(set(sorted_resources[rtype])) #----------------------------------------------------------- # set up varaibles to control batch processing loop #----------------------------------------------------------- total = len(sorted_resources[rtype]) batch_size = model.BATCH_PROCESS_SIZE # set to the size the model supports start = 0 #----------------------------------------------------------- # Loop until all batches have been processed #----------------------------------------------------------- while start < total: # get the batch end = start + min(batch_size, total - start) batch = { item.uuid: item for item in sorted_resources[rtype][start:end] } logger.info( "transfer resources (type: {}) batch {}:{}".format( rtype, start + 1, end)) self.transfer_items(session, src_key, dest_key, model, batch) # update the start and end of the slice for the next iteration start += batch_size
def generate_seed_data(): BASE.metadata.create_all(ENGINE) users = [["太郎"], ["次郎"], ["花子"]] todos = [[1, "title1", "description1", datetime.now()], [1, "title2", "description2", datetime.now()], [2, "title3", "description3", datetime.now()], [2, "title4", "description4", datetime.now()], [3, "title5", "description5", datetime.now()], [3, "title6", "description6", datetime.now()]] with session_scope() as session: for user in users: session.add(User(user[0])) for todo in todos: session.add( Todo(user_id=todo[0], title=todo[1], description=todo[2], deadline=todo[3]))
def insert_user(name: str) -> User: user = User(name) with session_scope() as session: session.add(user) session.flush() return user
async def get_things(self, data): with database.session_scope() as session: things = session.query(Thing).all() things = [thing_schema.dump(thing).data for thing in things] return things