def test_create_items(client, app): user = db_session.query(User).first() with app.test_request_context(): # Case unauthorized user response = create_item(client, ITEMS[0]) redirect_url = get_redirect_url(response) # It should redirect to home page assert redirect_url == url_for('auth.login') # Case authorized user g.current_user = user response = client.get(url_for('item.add_new_item')) # It should have a form assert 'form' in response.data response = create_item(client, ITEMS[0]) redirect_url = get_redirect_url(response) assert response.status_code == 302 assert redirect_url == url_for('item.get_item', item_id=1) # Case invalid form items_before = db_session.query(CatalogItem).all() response = create_item(client, {'name': ' ', 'description': '', 'catalog_id': 1}) items_after = db_session.query(CatalogItem).all() # Item should not be added assert len(items_before) == len(items_after) # It should response at current path assert not response.location
def load_items(n=50): """ :param n: number of items to insert into database :return: None """ conditions = ['clean', 'okay', 'torn', 'incomplete'] description = ["A test description\nThis sheet is cool"] sheets = db_session.query(Sheetmusic).all() users = db_session.query(User).all() random.seed(0) for i in range(n): sm = random.choice(sheets) user = random.choice(users) item = Item() item.user = user item.sheetmusic = sm item.condition = random.choice(conditions) item.description = random.choice(description) # add 4 images to each item item.images = [ItemImage("{}_{}".format(user.username, uuid.uuid4())) for _ in range(4)] db_session.add(item) # print(item) db_session.commit()
def get_by_id(cls, catalog_id): """Get a catalog by its id :param catalog_id: :return: Catalog """ return db_session.query(cls).filter(cls.id == catalog_id).first()
def get_by_id(cls, item_id): """Get a item by its id :param item_id: :return: CatalogItem """ return db_session.query(cls).filter(cls.id == item_id).first()
def before_request(): user_id = session.get('user_id') if user_id: g.current_user = db_session.query(User).filter( User.id == user_id).first() if not hasattr(g, 'current_user'): g.current_user = None
def find_all(user, contact_id): contact = db_session.query(User).get(contact_id) if not contact: raise Exception(u'메시지를 읽는데에 실패했습니다') know = db_session.query(user_know).filter( user_know.c.user_id == user.id and user_know.c.other_id == contact_id).first() if not know: raise Exception(u'메시지를 읽는데에 실패했습니다') condition1 = and_(Message.fromId == user.id, Message.toId == contact_id) condition2 = and_(Message.fromId == contact_id, Message.toId == user.id) messages = db_session.query(Message) messages = messages.filter(or_(condition1, condition2)) messages = messages.order_by(Message.time).all() return messages
def home_page(): """Route to home page""" catalogs = Catalog.get_all() items = db_session.query(CatalogItem).order_by(desc( CatalogItem.id)).limit(10).all() return render_template('index.html', type='index', catalogs=catalogs, items=items)
def test_item_page_json(client, app): create_items() item = db_session.query(CatalogItem).first() with app.test_request_context(): response = client.get(url_for('item.get_item_json', item_id=item.id)) data = json.loads(response.data) # It should render item list assert item.id == data['id'] and item.name == data['name']
def test_catalog_items_page(client, app): create_items() catalog = db_session.query(Catalog).first() with app.test_request_context(): response = client.get(url_for('catalog.catalog_items', catalog_id=catalog.id)) data = response.data # Board should in the item list assert ITEMS[0]['name'] in data # Helmet should not in the item list assert not ITEMS[1]['name'] in data
def test_catalog_items_json(client, app): create_items() catalog = db_session.query(Catalog).first() items = catalog.items with app.test_request_context(): response = client.get(url_for('catalog.catalog_items_json', catalog_id=catalog.id)) data = json.loads(response.data) # It should render item list assert len(data) == len(items) for index in range(len(data)): assert data[index]['id'] == items[index].id
def getAllRoomsWithCheck(user): res = [] for room in user.rooms: last_message = findLastMessage(room) last_check = db_session.query(user_in_room.c.last_check)\ .filter(user_in_room.c.room_id == room.id)\ .filter(user_in_room.c.user_id == user.id).first()[0] room_dict = room.serialize room_dict['lastMessage'] = last_message and last_message.serialize room_dict['lastCheck'] = str(last_check) res.append(room_dict) return res
def gconnect(): """Use google one time token to validate user""" code = request.data try: # Upgrade the authorization code into a credentials object oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='') oauth_flow.redirect_uri = 'postmessage' credentials = oauth_flow.step2_exchange(code) except FlowExchangeError: return render_json_error('Failed to upgrade the authorization code.', 401) # Check that the access token is valid. access_token = credentials.access_token url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' % access_token) result = json.loads(httplib2.Http().request(url, 'GET')[1]) # If there was an error in the access token info, abort. if result.get('error') is not None: return render_json_error(result.get('error'), 500) # Verify that the access token is valid for this app. if result['issued_to'] != CLIENT_ID: return render_json_error("Token's client ID does not match app's.", 401) # Get user info userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo" params = {'access_token': credentials.access_token, 'alt': 'json'} answer = requests.get(userinfo_url, params=params) data = answer.json() # Try to find user in our db user = db_session.query(User).filter(User.email == data['email']).first() # If user not in db, create new if not user: user = User(name=data['name'], email=data['email'], picture=data['picture']) db_session.add(user) db_session.commit() # Store the access token in the session for later use. session['access_token'] = credentials.access_token # Store user id for user authentication in next request session['user_id'] = user.id flash('Successfully login', 'info') return render_json({'message': 'Successfully login'})
def client(app): client = app.test_client() with app.app_context(): if not db_session.query(User)\ .filter(User.username == 'test').one_or_none(): init_db() db_session.add(User( username='******', password='******', )) db_session.commit() yield client
def load_user_request(request): try: auth = request.headers.get('Authorization') if not auth: return None if auth[:5] == 'Token': token = auth[6:] if len(token) == 64: user = db_session.query(User).filter( User.token == token).first() if user: return user except Exception as e: print e
def load_sheet_music(): with open(path.join(DATA_DIRECTORY, 'sheet_music.json'), 'r') as fh: data = json.load(fh) for sheet_music in data['sheet_music']: if not db_session.query(Sheetmusic).filter_by(title=sheet_music['title']).first(): instrumentation = sheet_music.pop('instrumentation', None) genres = sheet_music.pop('genre_tags', None) new_obj = Sheetmusic(**sheet_music) new_obj.parse_tags(instrumentation, Instrument, 'instrumentation') new_obj.parse_tags(genres, Genre, 'genre_tags') db_session.add(new_obj) # print("added", new_obj) db_session.commit()
def load_users(): with open(path.join(DATA_DIRECTORY, 'auth.json')) as fh: data = json.load(fh) for user in data['users']: if db_session.query(User).filter_by(email=user['email']).one_or_none() is None: addresses = user.pop('addresses') new_user_obj = User(**user) new_address_objs = [Address(**address) for address in addresses] new_user_obj.addresses = new_address_objs db_session.add(new_user_obj) # print("added", new_user_obj, new_address_objs) db_session.commit()
def getOneToOneRoom(first, second): current_user = first if first.id > second.id: first, second = second, first otor = db_session.query(OneToOneRoom).filter(OneToOneRoom.firstId == first.id)\ .filter(OneToOneRoom.secondId == second.id).first() if not otor: room = create(None, first) registerAsOneToOne(room, first, second) else: room = get(otor.roomId) if current_user not in room.users: room.users.append(current_user) db_session.commit() return room
def load_trades(n=10): """ Create and store several trade items. :param n: number of trades to insert into database :return: None """ random.seed(0) users = db_session.query(User).all() for i in range(n): from_user, to_user = random.sample(users, 2) from_item, to_item = random.choice(from_user.items), random.choice(to_user.items) trade = Trade(user_from_id=from_user.id, user_to_id=to_user.id, item_from=from_item, item_to=to_item) db_session.add(trade) db_session.commit()
def reset_all_tasks(): today = dt.datetime.today() weekday = today.weekday() month = today.month hour = today.hour for task in db_session.query(Task).all(): if not task.hours: continue schedule = json.loads(task.hours.replace("\'", "\"")) if not (schedule['month_of_year'] == '*' or month in set( [int(mnt) for mnt in schedule['month_of_year'].split(',')])): continue if not (schedule['day_of_week'] == '*' or weekday in set( [int(week) for week in schedule['day_of_week'].split(',')])): continue hours = set([int(hr) for hr in schedule['hour'].split(',')]) if not hour in hours: continue print(task) task.completed = False db_session.flush() db_session.commit()
def test_edit_items(client, app): create_items() item = db_session.query(CatalogItem).first() user = item.user with app.test_request_context(): g.current_user = user # Case get form response = client.get(url_for('item.edit_item', item_id=item.id)) assert response.status_code == 200 # Response should have item's info assert item.name in response.data # Case edit invalid form response = edit_item(client, item.id, {'name': ' ', 'description': '', 'catalog_id': 1}) # It should not update and render current from assert response.location is None # Case edit success edit_item(client, item.id, ITEMS[1]) edited_item = CatalogItem.get_by_id(item.id) assert (edited_item.name == ITEMS[1]['name'] and edited_item.description == ITEMS[1]['description'])
def test_delete_items(client, app): create_items() item = db_session.query(CatalogItem).first() user = item.user with app.test_request_context(): # Case unauthorized user g.current_user = None client.post(url_for('item.delete_item', item_id=item.id)) # Item should not be delete assert CatalogItem.get_by_id(item.id) is not None g.current_user = user response = client.get(url_for('item.delete_item', item_id=item.id)) # It should response form assert response.status_code == 200 assert 'form' in response.data # Case authorized user response = client.post(url_for('item.delete_item', item_id=item.id)) # It should redirect to home assert response.status_code == 302 # Item should be delete assert CatalogItem.get_by_id(item.id) is None
def get_all(cls): """Get all catalogs, order by name :return: [Catalog] """ return db_session.query(cls).order_by(cls.name).all()
def get(self, username=None, password=None): if not username or not password: return False user = db_session.query(UserTable).filter(UserTable.username==username).first() return user if user.check_password(password) else False
def catalog_items_json(catalog_id): """Render JSON for catalog's items""" items = db_session.query(CatalogItem).filter( CatalogItem.catalog_id == catalog_id) return render_json([i.serialize for i in items])
def load_user(user_id): return db_session.query(User).get(user_id)
def users(): with db(): user = db_session.query(User).filter_by(ref_type='partner').all() print(user) typer.echo("Hello users and i am video")
from app.db import db_session from app.models import Render import requests def dl_streamable(streamable_short, render_id='test'): api = 'https://api.streamable.com/videos/' r = requests.get(api + streamable_short) if r.status_code == 200: file_url = 'https:' + r.json()['files']['mp4']['url'] print('dl video...') rv = requests.get(file_url) open('app/download/renders/' + str(render_id) + '.mp4', 'wb').write(rv.content) else: print(render_id, r.status_code) for render in db_session.query(Render).filter(Render.streamable_short != None): dl_streamable(render.streamable_short, render.id)
def get_entries(self, start, end): return db_session.query(EntryTable).order_by( desc(EntryTable.created_date)).all()[start:end]
def get(self, username=None, password=None): if not username or not password: return False user = db_session.query(UserTable).filter( UserTable.username == username).first() return user if user.check_password(password) else False
def findLastMessage(room): return db_session.query(Message).filter(Message.roomId == room.id)\ .order_by(Message.time.desc()).first()
def del_patient(patient_name='Tomasz AA'): patient = db_session.query(Appointment)\ .filter(Appointment.patient_name == patient_name).first() db_session.delete(patient) db_session.commit()
def findByName(name): return db_session.query(Room).filter(Room.name == name).first()
def get(id): return db_session.query(Room).get(id)
def findConnectingUsersInRoom(room): result = db_session.query(user_in_room, User).filter(user_in_room.c.room_id == room.id)\ .join(User, User.id == user_in_room.c.user_id)\ .filter(User.connecting == 1).all() return [i.User for i in result]
def get_userrole(self, rolename): return db_session.query(UserRole).all()
def get_all_count(self): return db_session.query(EntryTable).count()
def get_entries(self): return db_session.query(ProjectTable).all()
def get_entries(self, start, end): return db_session.query(EntryTable).order_by(desc(EntryTable.created_date)).all()[start:end]