def add_category(restaurant_id): restaurant = Restaurant.get_by_id(restaurant_id) if restaurant is None: raise ApiError("Restaurant not exist") #if restaurant.user_id != current_user.id: # raise ApiError("you have not access to this restaurant") category = Category() name = request.json.get('name') if not name: raise ApiError(u"Введите имя") category.name = name category.restaurant_id = restaurant_id session.add(category) session.commit() template_dict = request.json.get('template') if template_dict is not None: add_template_dict_for_category(template_dict, category) return jsonify(category.serialize)
def create_restaurant(): # create new restaurant body = request.json name = body['name'] if name is None or name == "": raise ApiError(u"Введите название ресторана.") rest = Restaurant() rest.name = name rest.user_id = current_user.id created_rest = Restaurant.get_by_name(rest.name) if created_rest is not None: raise ApiError(u"Ресторан с данным именем уже существует.") location = body.get('location') if location is not None: rest.latitude = location.get('longitude') rest.latitude = location.get('latitude') session.add(rest) session.commit() return jsonify(rest.serialize)
def __authentication(self): ''' verify token from request ''' token = None if request.method == 'GET': token = self.req_args.get('token') else: token = self.req_data.get('token') if token == None: raise ApiError(401, 1, 'no token') if session.get(token) == None: raise ApiError(401, 2, 'token to exceed the time limit')
def check_login_args(email, password): if not email: raise ApiError(gettext(u"Введите email.")) if not re.match(r"[^@]+@[^@]+\.[^@]+", email): raise ApiError(gettext(u"Неправильный email.")) if not password: raise ApiError(gettext(u"Введите пароль.")) if password.lower() == password or password.upper( ) == password or not password.isalnum() or len(password) < 6: raise ApiError( gettext( u"Неправильный пароль. Пароль должен содержать минимум 6 символов, включая маленькую, большую букву и цифру." ))
def recognize_position(category_id): category = Category.get_by_id(category_id) if category is None: raise ApiError("category is not exist") template = json.loads(request.form.get("position")) properties = {} new_position = MenuItem(category_id=category_id) for property_json in template["properties"]: key = property_json["name"] image_file = request.files[key] if key == 'image': filename = generate_filename(prefix=key + str(category_id)) path = os.path.join(UPLOAD_FOLDER, filename) image_file.save(path) print(filename) print(path) new_position.image_name = filename else: property_value = image_to_string(image_file) properties[key] = property_value new_position.properties = str(properties) session.add(category) session.add(new_position) session.commit() return jsonify(new_position.serialize)
def process_response(self, success, callback, data, args): if success: retval = Util.decode_post(data) if not retval: Util.err_log("Unable to decode response: args=%s data=%s" % (str(args), data)) self.api_error[ args[0] ] = ApiError.badData("Unable to parse data") return if not Util.status_success(retval): self.api_error[ args[0] ] = ApiError.internalApiError(retval[ Constants.STATUS ]) else: self.api_data[ args[0] ] = retval[ Constants.RESULT ] if callback: callback(args, retval[ Constants.RESULT ]) else: self.api_error[ args[0] ] = ApiError.connectionError(data)
def line_cached(line_id): try: return Response(line_service.get_line(int(line_id)), headers={'Content-Type': 'text/html'}, status=200) except OutOfRangeException as e: raise ApiError(e, status_code=413)
def line_basic(line_id): try: return Response(basic_line_service.get_line(int(line_id)), headers={'Content-Type': 'text/html'}, status=200) except IndexError as e: raise ApiError(e, status_code=413)
def exec_curl2(version, req, args): s = cStringIO.StringIO() c = Util.fun_wrapper(req, args) c.setopt(pycurl.WRITEFUNCTION, s.write) try: c.perform() except Exception, e: err = c.errstr() ConnPool.put(c) return [ False, None, Util.gen_error(version, ApiError.connectionError(err)), None ]
def restaurant(restaurant_id): rest = Restaurant.get_by_id(restaurant_id) if rest is None: raise ApiError("Restaurant is not exist") if request.method == "GET": return jsonify(rest.full_serialize) else: session.delete(rest) session.commit() return jsonify(success=True)
def login(): email = request.json.get('email') password = request.json.get('password') check_login_args(email, password) registered_user = session.query(User).filter(User.email == email).first() if registered_user is None: raise ApiError( gettext(u"Пользователь с ввенными данными не зарегистрирован")) if registered_user.password != password: raise ApiError(gettext(u"Неправильная комбинация почты и пароля")) flask.flash('Logged in successfully.') registered_user.fir_token = request.json.get('firToken') login_user(registered_user) return jsonify(registered_user.serialize)
def social_login(): json = request.json social_id = json.get('socialId') email = json.get('email') token = json.get('token') platform = json.get('platform') fir_token = json.get('firToken') registered_user = User.get_by_social_id(social_id) if registered_user is None: if platform == "FB": json = fb_info(social_id, token) else: json = vk_info(social_id, token) if json is None: raise ApiError(u"Произошла ошибка авторизации") image_url = json.get('image_url') first_name = json.get("first_name") last_name = json.get("last_name") if email is None or len(email) == 0: email = json.get('email') print(image_url) user = User(social_id=social_id, email=email, name=first_name, last_name=last_name, image_url=image_url, fir_token=fir_token) session.add(user) session.commit() login_user(user) return jsonify(user.serialize) registered_user.fir_token = fir_token login_user(registered_user) return jsonify(registered_user.serialize)
def update_item(item_id): item = MenuItem.get_by_id(item_id) if item is None: raise ApiError("item is not exist") if request.method == 'DELETE': session.delete(item) session.commit() return jsonify(success=True) dict = request.json.get('properties') print(dict) print(str(dict)) item.properties = str(dict) session.add(item) session.commit() return jsonify(item.serialize)
def add_template_dict_for_category(template_dict, category): name = template_dict.get('name') if name is None: name = category.name template = OcrTemplate(name=name, user_id=current_user.id) session.add(template) session.commit() props = template_dict['properties'] if len(props) == 0: raise ApiError("Необходимо добавить как минимум одно свойство.") template.add_properties(props) session.add(template) session.commit() category.template_id = template.id session.add(category) session.commit()
def change_edit_user(rest_id, user_id): restaurant = Restaurant.get_by_id(rest_id) if restaurant.user_id != current_user.id: raise ApiError("Меню " + restaurant.name + " не принадлежит данному пользователю!") user = User.get_by_id(user_id) add_access = request.method == 'POST' if add_access: restaurant.edit_users.append(user) else: restaurant.edit_users.remove(user) notify_user(user, current_user, restaurant, add_access) session.add(restaurant) session.add(user) session.commit() return jsonify([user.serialize for user in restaurant.edit_users])
for item in arr: ins = VerifyParam(item) if not fn(ins): if ignore_mismatch: continue else: raise excep_class ret.append(ins.get()) return ret if __name__ == '__main__': from api_error import ApiError print Verify.dict({'vlan': '123'}, { 'vlan': (lambda x: x.type('int') and x >= 1 and x <= 4095, ApiError(400, 1, 'invalid vlan')), 'name?': (lambda x: x.type('string') and len(x) < 15 and x.match(r'^\w+\d+$'), ApiError(400, 2, 'invalid name')), }) print Verify.array([1, 2, 3, 4, 5, 'a', '7', '8'], lambda x: x.type('int') and x > 0, ApiError(400, 1, 'invalid key'), True) pass
def check_register_args(email, password, name): check_login_args(email, password) if name is None: raise ApiError(gettext(u"Введите имя."))
def exec_curl(version, req, args): s = cStringIO.StringIO() c = Util.fun_wrapper(req, args) c.setopt(pycurl.WRITEFUNCTION, s.write) try: c.perform() except Exception, e: err = c.errstr() ConnPool.put(c) return [ False, None, Util.gen_error(version, ApiError.connectionError(err)) ] if c.getinfo(pycurl.HTTP_CODE) != 200: err = c.errstr() ConnPool.put(c) return [ False, None, Util.gen_error(version, ApiError.connectionError(err)) ] ConnPool.put(c) ret = Util.decode_post(s.getvalue()) if not ret: return [ False, None, Util.gen_error(version, ApiError.badData("Unable to parse response body")) ] if not Util.status_success(ret): return [ False, None, Util.gen_error(version, ApiError.internalApiError(ret[ Constants.STATUS ])) ] return [ True, ret[ Constants.RESULT ], None ] def exec_curl2(version, req, args): s = cStringIO.StringIO() c = Util.fun_wrapper(req, args) c.setopt(pycurl.WRITEFUNCTION, s.write) try:
def raise_default_error(status_code): raise ApiError("Произошла ошибка при выполнении запроса", status_code)