def groceries(): if request.method == 'POST': #makes new grocery grocery = Grocery.from_json(request.json) session = Session() session.add(grocery) session.commit() return grocery.__json__() elif request.method == 'GET': #grabs all groceries from SQL database session = Session() result = session.query(Grocery).order_by(Grocery.grocery_id).all() return {'groceries': [grocery.__json__() for grocery in result]}
async def step(self, obj): try: nowms = int(time() * 1000) self.log(f'Step ms {nowms}') state = self.inner_step(obj, nowms) if state != DEVSTATE_INVALIDSTEP: if not self.session: self.session = Session(device=self.deviceid, user=self.userid, settings=self.conf, datestart=nowms) if (await self.session.to_db(self.db, True)): self.dispatch("on_session", self.session) elif self.main_session_id < 0: self.main_session_id = -self.main_session_id self.session.mainid = self.main_session_id await self.session.to_db(self.db, True) self.nUpdates = self.nUpdates + 1 try: commit = nowms - self.last_commit > 30000 obj.session = self.session.rowid await obj.to_db(self.db, commit) if commit: self.last_commit = nowms except Exception: self.error(f'Commit error: {traceback.format_exc()}') obj.s('updates', self.nUpdates) return state except Exception: self.error(f'Step error: {traceback.format_exc()}') return DEVSTATE_INVALIDSTEP
def setUp(self): from db.session import Session, DBState from db.models import User, Item, DiscuzMember, DiscuzMemberCount from db.base import Model Model.metadata.drop_all(DBState.engine) Model.metadata.create_all(DBState.engine) s = Session() [ s.add(i) for i in [ User(id=1, username='******', jiecao=100000, ppoint=1000, title='', email='*****@*****.**'), User(id=2, username='******', jiecao=100000, ppoint=1000, title='', email='*****@*****.**'), DiscuzMember(uid=1, username='******'), DiscuzMember(uid=2, username='******'), DiscuzMemberCount(uid=1, jiecao=100000), DiscuzMemberCount(uid=2, jiecao=100000), Item(id=1, owner_id=1, sku='foo', status='backpack'), Item(id=2, owner_id=2, sku='bar', status='backpack'), ] if not options.freeplay or 'DiscuzMember' not in i.__class__.__name__ ] s.commit()
def grocery_list_items(): if request.method == 'POST': grocery_list_item = GroceryListItem.from_json(request.json) session = Session() session.add(grocery_list_item) session.commit() return grocery_list_item.__json__()
def add_iventory(): """Add parts to DB.""" session = Session() inventory = ( StockPart( part=Part(name='Valve Body 32"'), count=100, ), StockPart( part=Part(name='Valve Body 12"'), count=50, ), StockPart( part=Part(name='Valve Slip 32"'), count=90, ), StockPart( part=Part(name='Valve Slip 12"'), count=50, ), StockPart( part=Part(name='Screw 14 x 2 1/2"'), count=1000, ), ) session.add_all(inventory) session.commit()
def users(): if request.method == 'POST': user = User.from_json(request.json) session = Session() session.add(user) session.commit() return user.__json__()
def reduce_count_of_stock_part(part_id: int, reduction: int) -> None: """Increase count of a part in stock.""" # TODO: prevent reduction below 0. session: Session = Session() part = session.query(StockPart).filter(StockPart.id_ == part_id).one() part.count -= reduction session.commit()
def authenticate_api_key(key, secret): """Authenticate an API key""" s = Session() user = s.query(User).filter_by(api_key=key, api_secret=secret).first() s.close() return user
def grocery_list(grocery_list_id): if request.method == 'GET': session = Session() result = session.query(GroceryList).filter_by(grocery_list_id=grocery_list_id).first() if result is None: return ('Grocery list not found.', 404) else: return result.__json__()
def search(grocery_name): if request.method == 'GET': session = Session() result = session.query(Grocery).filter_by(name=grocery_name).first() if result is None: return ('Grocery not found.', 404) else: return result.__json__()
def create_new_stock_part(name: str, count: int) -> None: """Create new part in stock.""" session: Session = Session() new_part: StockPart = StockPart( part=Part(name=name), count=count, ) session.add(new_part) session.commit()
def grocery_list_item(grocery_list_item_id): if request.method == 'GET': session = Session() result = session.query(GroceryListItem).filter_by( grocery_list_item_id=grocery_list_item_id).first() if result is None: return ('Grocery list item not found.', 404) else: return result.__json__() elif request.method == 'DELETE': session = Session() grocery_list_item = session.query(GroceryListItem).filter_by( grocery_list_item_id=grocery_list_item_id).first() if grocery_list_item is None: return ('Grocery list item not found.', 404) else: session.delete(grocery_list_item) session.commit() return grocery_list_item.__json__()
def user_lists(user_id): if request.method == 'GET': #Retrieves all of a user's lists session = Session() result = session.query(GroceryList).filter_by(user_id=user_id).all() response = [] for grocery_list in result: json = grocery_list.__json__() grocery_list_items_preview = ( session.query(GroceryListItem).order_by( GroceryListItem.grocery_list_item_id)[:SAMPLE_IMAGES]) json['grocery_list_items_preview'] = grocery_list_items_preview response.append(json) return {'grocery_lists': response} elif request.method == 'POST': #Creates a new list for the user grocery_list = GroceryList(user_id=user_id, name=request.json['name']) session = Session() session.add(grocery_list) session.commit() return grocery_list.__json__()
def user_list(user_id, list_id): if request.method == 'GET': #Grabs all items from a user's grocery list session = Session() result = session.query(GroceryListItem).filter_by( grocery_list_id=list_id).order_by( GroceryListItem.grocery_list_item_id).all() if result is None: return ('Grocery not found.', 404) else: return { 'grocery_items': [grocery_list_item.__json__() for grocery_list_item in result] } elif request.method == 'POST': #Adds an item to a user's grocery list grocery_list_item = GroceryListItem( grocery_list_id=list_id, grocery_id=request.json['grocery_id']) session = Session() session.add(grocery_list_item) session.commit() return grocery_list_item.__json__()
def authenticate_auth_token(token): """Authenticate a jwt auth token""" try: payload = jwt.decode(token, TOKEN_SECRET_KEY) except: return None user_id = payload["sub"] s = Session() user = s.query(User).filter_by(id=user_id).first() s.close() return user
def ListCustomers(self, request, context): """ List all customers :param request: A ListCustomersRequest :param context: the grpc context """ db = Session() customers = db.query(Customer).all() return customers_pb2.ListCustomersResponse( customers=[ c.to_message(customers_pb2.Customer) for c in customers ], status=status_pb2.Status(code=200))
def create_user(params: dict): """ Create a user """ password_hash = hash_password(params.get("password")) del params["password"] params["password_hash"] = password_hash user = models.User(**params) db = Session() db.add(user) db.commit() db.close() return user
def CreateCustomer(self, request, context): """ Create a customer :param request: A CreateCustomerRequest :param context: The grpc context """ # Validate customer errors = validate_customer(request.customer) if errors: return customers_pb2.CreateCustomerResponse( status=status_pb2.Status(code=400, data_errors=errors), ) # Add customer to database db = Session() customer = Customer(request.customer) try: db.add(customer) db.commit() return customers_pb2.CreateCustomerResponse( customer=customer.to_message(customers_pb2.Customer), status=status_pb2.Status(code=200), ) except Exception as e: db.rollback() return customers_pb2.CreateCustomerResponse( status=status_pb2.Status(code=500, runtime_errors=[ exception_to_runtime_error(e) ]), ) finally: db.close()
def get_db() -> Generator: try: db = Session() yield db finally: db.close()
async def db_session_middleware(request: Request, call_next): request.state.db = Session() response = await call_next(request) request.state.db.close() return response
"name", "age", "password", "coins", "user_type", "coin_limit", "initial_bet", "reward" ] account_schema = { "accounts": { "name": "TEXT", "age": "INTEGER", "password": "******", "coins": "INTEGER", "user_type": "TEXT", "coin_limit": "INTEGER" } } sess = Session(':memory:') sess.createTable(**account_schema) a = UserInfo2(name='Guest') a.initiate_name() #======================================DATABASE====================================== conn = sqlite3.connect(':memory:') c = conn.cursor() c.execute( 'CREATE TABLE IF NOT EXISTS Accounts (name TEXT, age INTEGER, password TEXT, coins INTEGER, user_type TEXT, coin_limit INTEGER)' ) c.execute("SELECT * FROM Accounts") data = c.fetchall() c.execute("SELECT * FROM Accounts WHERE name = 'Administrator'") verify_data = c.fetchone()
def get_inventory() -> List[StockPart]: """Return list of all parts in the inventory.""" session: Session = Session() return session.query(StockPart).all()
def before_request(): g.db = Session()
def increase_count_of_stock_part(part_id: int, increase: int) -> None: """Increase count of a part in stock.""" session: Session = Session() part = session.query(StockPart).filter(StockPart.id_ == part_id).one() part.count += increase session.commit()
def get_part_ids_from_inventory() -> List[int]: """Return list of part ids.""" session: Session = Session() rows = session.query(StockPart.id_).all() return [row.id_ for row in rows]