def get_user_shift(): user_id = request.args.get('user_id', default=-1, type=int) table_id = request.args.get('table_id', default=-1, type=int) if user_id == -1 or table_id == -1: session.close() frame = inspect.currentframe() abort(400, {'code': frame.f_lineno, 'msg': 'IDの指定方法が間違っています', 'param': None}) shifts = session.query(UserShift, Shift).join(Shift).filter( UserShift.user_id == user_id, UserShift.shift_table_id == table_id ).all() shift_results = [] for shift in shifts: shift_results.append({ 'user': shift[0].user.name, 'shift': shift[1].name, 'date': str(shift[0].date), 'start': None if shift[1].start is None else str(shift[1].start), 'end': None if shift[1].end is None else str(shift[1].end) }) session.close() return jsonify({'results': shift_results}), 200
def get_search_init(): access_user = session.query(User).filter( User.code == api_basic_auth.username()).one() shift_categories = session.query(ShiftCategory).filter( ShiftCategory.company_id == access_user.company_id).all() shifts = session.query(Shift).join(ShiftCategory).filter( ShiftCategory.company_id == access_user.company_id).all() users = session.query(User).filter( User.company_id == access_user.company_id).all() tables = session.query(ShiftTable).filter( ShiftTable.company_id == access_user.company_id).all() session.close() return jsonify({ 'results': { 'category': [{ 'id': category.id, 'name': category.name } for category in shift_categories], 'shift': [{ 'id': shift.id, 'name': shift.name } for shift in shifts], 'user': [{ 'id': user.id, 'name': user.name } for user in users], 'table': [{ 'id': table.id, 'title': table.title } for table in tables] } }), 200
def get(): admin_user = session.query(User).filter( User.code == api_basic_auth.username()).one() if admin_user.role.name != 'admin': session.close() frame = inspect.currentframe() abort(403, {'code': frame.f_lineno, 'msg': '権限がありません', 'param': None}) users_role = session.query(User, Role).join(Role).filter( User.company_id == admin_user.company_id).order_by( User.order.asc()).all() company = session.query(Company).filter( Company.id == admin_user.company_id).one() users = [] for user, role in users_role: users.append({ 'name': user.name, 'code': user.code, 'order': user.order, 'role': role.name, 'password': '******' if user.is_authed else user.password }) session.close() return jsonify({'results': {'users': users, 'company': company.code}}), 200
def add_starting_links(start, to_be_visited=[]): Base.metadata.create_all(engine) response = requests.get(start, timeout=10) html = response.content.decode('utf-8') soup = BeautifulSoup(html, 'html.parser') for link in soup.find_all('a'): try: link_string = link.get('href') except requests.exceptions.ConnectionError: pass if link_string is not None: if 'http' in link_string and str(link_string) not in to_be_visited: try: can_procede = True server, can_procede = timeout_error(link_string) if can_procede is True: to_be_visited = add_to_database(link_string, server, 0, to_be_visited) except (requests.exceptions.ConnectionError, KeyError, requests.exceptions.InvalidSchema, requests.exceptions.InvalidURL): pass if 'link.php' in link_string and str(link_string) not in to_be_visited: try: url = 'https://register.start.bg/' link_string = url + link_string # r = requests.get(link_string) # server = r.headers['Server'] can_procede = True server, can_procede = timeout_error(link_string) if can_procede is True: to_be_visited = add_to_database(link_string, server, 0, to_be_visited) except (requests.exceptions.ConnectionError, KeyError, requests.exceptions.InvalidSchema, requests.exceptions.InvalidURL): pass session.close()
def get_news(channel: int): urls = [ os.environ.get('LENTA_URL'), os.environ.get('INTERFAX_URL'), os.environ.get('KOMMERSANT_URL'), os.environ.get('M24_URL') ] limit = 3 feed = feedparser.parse(urls[channel]) all_data = feed["items"] for event in all_data: if limit > 0: title = event['title'] link = event['link'] text = event['description'] pub_date = event['published'] if channel == 0 or channel == 3: image = event['links'][1]['href'] else: image = 'no image' news = News(title=title, link=link, text=text, pub_date=pub_date, image=image) session.add(news) session.commit() limit -= 1 else: session.close() return
def post(): # schema = {'type': 'object', # 'properties': # {'id': {'type': 'integer', 'minimum': 0}}, # 'required': ['id'] # } # try: # validate(request.json, schema) # except ValidationError as e: # return jsonify({'msg': e.message}), 400 # return str(type(request.json['id'])) user = session.query(User).filter( User.id == request.json['id']).one_or_none() if user is None: return jsonify({'msg': 'User Not Found'}), 404 pull = Pull(user_id=user.id) session.add(pull) session.commit() session.close() return jsonify({'id': request.json['id']}), 200
def get(self): request = Option.parser.parse_args() return_list = [] if request['pk'] == None: option = session.query(models.Option).all() session.close() # 데이터가 존재하지 않기 때문에 404 반환 if option == None: return Response(status=404) # 데이터베이스 객체 딕셔너리로 파싱 작업 for i in option: return_list.append({ 'optionPK': i.option_pk, 'optionName': i.option_name, 'optionPrice': i.option_price, 'optionSoldout': i.option_soldout }) else: try: option = session.query(models.Option).filter( models.Option.option_pk == request['pk']).first() session.close() # 데이터베이스 객체 딕셔너리로 파싱 작업 return_list.append({ 'optionPK': option.option_pk, 'optionName': option.option_name, 'optionPrice': option.option_price, 'optionSoldout': option.option_soldout }) except: # 해당 pk값을 가진 데이터가 존재하지 않기 때문에 404 반환 return Response(status=404) return {'data': return_list}, 200
def get(): user = session.query(User).filter( User.code == api_basic_auth.username()).one_or_none() if user is None: session.close() frame = inspect.currentframe() abort(404, { 'code': frame.f_lineno, 'msg': '指定されたユーザは存在しません', 'param': None }) salary_tables_results = session.query(Salary, ShiftTable)\ .join(ShiftTable)\ .filter(Salary.user_id == user.id)\ .order_by(Salary.created_at.asc())\ .all() results = [] for salary, table in salary_tables_results: results.append({'pay': salary.pay, 'title': table.title}) session.close() return jsonify({'results': results}), 200
def get(): user = session.query(User).filter( User.code == api_basic_auth.username()).one_or_none() session.close() return jsonify({ 'results': { 'daytime_start': None if user.daytime_start is None else user.daytime_start.strftime("%H:%M"), 'daytime_end': None if user.daytime_end is None else user.daytime_end.strftime("%H:%M"), 'daytime_wage': None if user.daytime_wage is None else user.daytime_wage, 'night_start': None if user.night_start is None else user.night_start.strftime("%H:%M"), 'night_end': None if user.night_end is None else user.night_end.strftime("%H:%M"), 'night_wage': None if user.night_wage is None else user.night_wage } }), 200
def get_(user_id): results = [] promises = session.query(Promise, User).filter( or_(Promise.master_user_id == user_id, Promise.slave_user_id == user_id), or_(User.id == Promise.master_user_id, User.id == Promise.slave_user_id), Promise.is_done == True, User.id != user_id).all() promises.sort(key=lambda tmp_promise: tmp_promise[1].id) for user_id, promise_list in groupby( promises, key=lambda tmp_promise: tmp_promise[1].id): user = [ tmp_promise_user[1] for tmp_promise_user in promises if tmp_promise_user[1].id == user_id ][0] results.append({ 'count': len(list(promise_list)), 'img': '{}/{}'.format(HOST_TOP, user.profile), 'name': user.name, 'user_id': user.id }) session.close() return jsonify({'results': results}), 200
def session_clear(exception): if exception and session.is_active: session.rollback() else: session.commit() session.close()
async def update_tasks(tasks: List[Task]): for new_task in tasks: task = session.query(TaskTable).filter( TaskTable.id == new_task.id).first() task.title = new_task.title session.commit() session.close()
def post(): schema = { 'type': 'object', 'properties': { 'user_id': { 'type': 'integer', 'minimum': 0 } }, 'required': ['user_id'] } try: validate(request.json, schema) except ValidationError as e: return jsonify({'msg': e.message}), 400 user = session.query(User).filter( User.id == request.json['user_id']).one_or_none() if user is None: return jsonify({'msg': 'User Not Found'}), 404 walk = Walk(user_id=user.id) session.add(walk) session.commit() session.close() return jsonify({'walk_id': walk.id}), 200
def update_token(): schema = { 'type': 'object', 'properties': { 'token': { 'type': 'string', 'pattern': '^[0-9a-f]{64}$' } }, 'required': ['token'] } try: validate(request.json, schema) except ValidationError as e: session.close() frame = inspect.currentframe() abort(400, {'code': frame.f_lineno, 'msg': e.message, 'param': None}) user = session.query(User).filter( User.code == api_basic_auth.username()).one() user.token = request.json['token'] session.commit() session.close() return jsonify({'msg': 'OK'}), 200
def update(): schema = {'type': 'object', 'properties': {'is_shift_import': {'type': 'boolean'}, 'is_comment': {'type': 'boolean'}, 'is_update_shift': {'type': 'boolean'}, }, 'required': ['is_shift_import', 'is_comment', 'is_update_shift'] } try: validate(request.json, schema) except ValidationError as e: session.close() frame = inspect.currentframe() abort(400, {'code': frame.f_lineno, 'msg': e.message, 'param': None}) user = session.query(User).filter(User.code == api_basic_auth.username()).one() user.is_shift_import_notification = request.json['is_shift_import'] user.is_comment_notification = request.json['is_comment'] user.is_update_shift_notification = request.json['is_update_shift'] session.commit() session.close() return jsonify({ 'is_shift_import': user.is_shift_import_notification, 'is_comment': user.is_comment_notification, 'is_update_shift': user.is_update_shift_notification }), 200
def get(self): request = Category.parser.parse_args() return_list = [] if request['category_pk'] == None: category = session.query(models.Category).all() if category == None: # 데이터가 존재하지 않기 때문에 404 반환 return Response(status=404) # 데이터베이스 객체 딕셔너리로 파싱 작업 for i in category: return_list.append({ 'categoryPk': i.category_pk, 'categoryName': i.category_name }) else: try: category = session.query(models.Category).filter( models.Category.category_pk == request['pk']).first() # 데이터베이스 객체 딕셔너리로 파싱 작업 return_list.append({ 'categoryPk': category.category_pk, 'categoryName': category.category_name }) except: #filter함수에 반환 값이 없으면 오류 발생으로 404 반환 return Response(status=404) session.close() return {'data': return_list}, 200
def get(user_id): # user_id ユーザID promises = session.query(Promise, User).filter( or_(Promise.master_user_id == user_id, Promise.slave_user_id == user_id), or_(User.id == Promise.master_user_id, User.id == Promise.slave_user_id), User.id != user_id, Promise.is_done == False ).order_by(Promise.created_at.desc()).all() results = [] for promise, user in promises: results.append({ 'id': promise.id, 'created_at': promise.created_at.strftime('%Y年%m月%d日'), 'limited_at': '' if promise.limit_date is None else promise.limit_date.strftime('%Y年%m月%d日'), 'calendar_date': '' if promise.limit_date is None else promise.limit_date.strftime('%Y/%m/%d %H:%M:%S'), 'img': '{}/{}'.format(HOST_TOP, user.profile), 'name': user.name, 'content': promise.content, 'is_master': True if str(promise.master_user_id) == str(user_id) else False, 'one_side_done': None if promise.one_side_done_user_id is None else promise.one_side_done_user_id }) session.close() return jsonify({'results': results})
def get_export_init(): access_user = session.query(User).filter(User.code == api_basic_auth.username()).one() company_users = session.query(User).filter( User.company_id == access_user.company_id ).all() follow = session.query(Follow, User) \ .join(User, Follow.follow_id == User.id) \ .filter(Follow.user_id == access_user.id) \ .one_or_none() if follow: follow_user = {'id': follow[1].id, 'name': follow[1].name} else: follow_user = None company_tables = session.query(ShiftTable).filter(ShiftTable.company_id == access_user.company_id).all() session.close() return jsonify({ 'me': {'id': access_user.id, 'name': access_user.name}, 'follow': follow_user, 'users': [{'name': user.name, 'id': user.id} for user in company_users], 'tables': [{'id': table.id, 'title': table.title} for table in company_tables] }), 200
def get(): user = session.query(User).filter( User.code == api_basic_auth.username()).one() category_results = session.query(ShiftCategory).filter( ShiftCategory.company_id == user.company_id).all() scheme_results = session.query(ColorScheme).filter( ColorScheme.user_id == user.id).all() results = [] for category in category_results: scheme_category_match_result = [ x for x in scheme_results if x.shift_category_id == category.id ] tmp = {'category_id': category.id, 'category_name': category.name} if len(scheme_category_match_result) == 0: tmp['hex'] = None tmp['color_scheme_id'] = None else: tmp['hex'] = scheme_category_match_result[0].hex tmp['color_scheme_id'] = scheme_category_match_result[0].id results.append(tmp) session.close() return jsonify({'results': results}), 200
def get(self): data = Order.parser.parse_args() result = None if data['pk']: # 만약 특정 pk 쿼리라면 order_sql = """ SELECT ORD.order_pk, DATE_FORMAT(order_time, '%Y-%m-%d %H:%i:%s') as order_time, completed, total_price, menu_name, quantity, option_name FROM ORDERS ORD JOIN ORDER_PRODUCTS ORD_PRD USING(order_pk) LEFT JOIN ORDER_OPTIONS ORD_OP USING (product_pk) JOIN MENUS M ON (M.menu_pk = ORD_PRD.order_menu_pk) LEFT JOIN OPTIONS USING (option_pk) WHERE ORD.order_pk = {pk} """.format(pk=data['pk']) else: order_sql = """ SELECT ORD.order_pk, DATE_FORMAT(order_time, '%Y-%m-%d %H:%i:%s') as order_time, completed, total_price, menu_name, quantity, ORD_PRD.product_pk, option_name FROM ORDERS ORD JOIN ORDER_PRODUCTS ORD_PRD USING(order_pk) LEFT JOIN ORDER_OPTIONS ORD_OP USING (product_pk) JOIN MENUS M ON (M.menu_pk = ORD_PRD.order_menu_pk) LEFT JOIN OPTIONS USING (option_pk) WHERE ORD.order_time between DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 DAY), '%Y-%m-%d') and DATE_FORMAT(DATE_ADD(NOW(), INTERVAL 1 SECOND), '%Y-%m-%d %H:%i:%s') ORDER BY ORD.order_pk, M.menu_pk; """ result = session.execute(order_sql).fetchall() session.close() result = query_to_dict(result) if not result[0]: # 쿼리 결과가 없을 경우 return Response(status=404) result = many_to_one(result) return {'orderList': result}, 200
def insertdd(): # walkをinsert # for i in range(1, 13): # hour = random.randint(8, 17) # miniute = random.randint(0, 59) # start_walk_datetime = datetime(2018, 5, i, hour, miniute, 0) # end_walk_datetime = start_walk_datetime + timedelta(minutes=40) # print(start_walk_datetime, end_walk_datetime) # # walk = Walk(user_id=1, started_at=start_walk_datetime, ended_at=end_walk_datetime) # session.add(walk) # session.commit() # session.close() for day in range(1, 13): for hour in range(8, 18): for miniute in range(0, 59): if random.randint(1, 3) % 2 == 0: pull_datetime = datetime(2018, 5, day, hour, miniute, 0) print(pull_datetime) # if random.randint(1, 11) % 2: # break # pull_datetime = datetime(2018, 4, day, hour, miniute, 0) # # print(pull_datetime) # pull = Pull(user_id=1, created_at=pull_datetime) session.add(pull) session.commit() session.close()
def get(): user = session.query(User).filter( User.code == api_basic_auth.username()).one() category_shift_results = session.query(ShiftCategory, Shift)\ .outerjoin(Shift, ShiftCategory.id == Shift.shift_category_id) \ .filter(ShiftCategory.company_id == user.company_id)\ .order_by(ShiftCategory.id.asc())\ .all() results = [] current_category = category_shift_results[0][0] tmp_shifts = [] for category, shift in category_shift_results: if current_category == category: if shift is None: tmp_shifts = [] else: tmp_shifts.append({ 'id': shift.id, 'name': shift.name, 'start': None if shift.start is None else shift.start.strftime("%H:%M"), 'end': None if shift.end is None else shift.end.strftime("%H:%M") }) else: results.append({ 'category_name': current_category.name, 'category_id': current_category.id, 'shifts': tmp_shifts }) if shift is None: tmp_shifts = [] else: tmp_shifts = [{ 'id': shift.id, 'name': shift.name, 'start': None if shift.start is None else shift.start.strftime("%H:%M"), 'end': None if shift.end is None else shift.end.strftime("%H:%M") }] current_category = category results.append({ 'category_name': current_category.name, 'category_id': current_category.id, 'shifts': tmp_shifts }) session.close() return jsonify({'results': results}), 200
def login(): user_role_results = session.query(User, Role).join(Role).filter(User.code == api_basic_auth.username()).one_or_none() session.close() if user_role_results is not None: return jsonify({'user_code': user_role_results[0].code, 'role': user_role_results[1].name}), 200 else: frame = inspect.currentframe() abort(404, {'code': frame.f_lineno, 'msg': 'ログインに失敗しました。ログイン情報を再確認してください。', 'param': None})
def get(): user = session.query(User).filter(User.code == api_basic_auth.username()).one_or_none() session.close() return jsonify({ 'is_shift_import': user.is_shift_import_notification, 'is_comment': user.is_comment_notification, 'is_update_shift': user.is_update_shift_notification }), 200
def patch(self): data = Order.parser.parse_args() if data['pk']: instance = session.query(models.Order).get(data['pk']) instance.completed = True session.commit() else: Response(status=400) # pk 값 없음 에러 전달 session.close() return Response(status=204) # 처리 완료 코드 전달
def delete(self): request = Category.parser.parse_args() #delete에 필요한 값인 category pk가 없으면 400 반환 if request['category_pk'] == None: return Response(status=400) sql = f"delete from categories where category_pk = {request['category_pk']}" session.execute(sql) session.commit() session.close() return Response(status=200)
def get(): try: session.connection() except exc.SQLAlchemyError: abort(500) session.close() session.close() return Response(status=200)
def delete(self): request = Menu.parser.parse_args() #delete에 필요한 값인 'pk'가 없으면 400 반환 if request['pk'] == None: return Response(status=400) sql = f"delete from menus where menu_pk = {request['pk']}" session.execute(sql) session.commit() session.close() return Response(status=200)
def get(): user = session.query(User).filter(User.id == 1).one_or_none() if user is None: return jsonify({'msg': 'User Not Found'}), 404 pull = Pull(user_id=user.id) session.add(pull) session.commit() session.close() return jsonify({'msg': 'Success'}), 200
def delete(self): request = Option.parser.parse_args() #post에 필요한 값인 'option_pk' 가 없으면 400 반환 if request['option_pk'] == None: return Response(status=400) session.execute("DELETE FROM OPTIONS WHERE option_pk = {}".format( request['option_pk'])) session.commit() session.close() return Response(status=200)
try: print json.dumps(json.loads(d.text), indent=2) except: print d.text d = requests.get("http://localhost:7000/restaurants/casa-bonita/dishes") try: print json.dumps(json.loads(d.text), indent=2) except: print d.text d = requests.get("http://localhost:7000/dishes/burrito") try: print json.dumps(json.loads(d.text), indent=2) except: print d.text i = requests.get("http://localhost:7000/ingredients/beans") try: print json.dumps(json.loads(i.text), indent=2) except: print i.text r = requests.delete("http://localhost:7000/restaurants") r = requests.delete("http://localhost:7000/users") r = requests.delete("http://localhost:7000/ingredients") session.close()
def shutdown_session(exception=None): session.close()