Пример #1
0
    def put(self):
        """PUT method to create or update a blueprint."""

        data = self.parser.parse_args()

        blueprint = BlueprintModel.find_by_image(data['image'])
        if blueprint:
            blueprint.name = data['name']
            blueprint.image = data['image']
            blueprint.description = data['description']
        else:
            blueprint = BlueprintModel(name=data['name'],
                                       description=data['description'],
                                       image=data['image'])

        try:
            blueprint.save_to_db()
        except:
            return response(
                500, None,
                f"An error occured while trying to update blueprint {data['name']}.",
                None), 500

        return response(201, f"Blueprint {data['name']} has been updated.",
                        None, blueprint.json()), 201
Пример #2
0
    def delete(self, _id):
        """DELETE method to delete blueprint by ID."""

        try:
            blueprint = BlueprintModel.find_by_id(_id)
        except:
            return response(
                500, None,
                f"An error occured while trying to delete blueprint {blueprint.name}.",
                None), 500

        if blueprint:
            try:
                blueprint.delete_from_db()
            except:
                return response(
                    500, None,
                    f"An error occured while trying delete blueprint {data['name']}.",
                    None), 500
            return response(200,
                            f"Blueprint {blueprint.name} has been deleted.",
                            None, None), 200

        return response(404, None, f"Blueprint with id {_id} does not exist.",
                        None), 404
Пример #3
0
    def post(self):
        upload_folder = os.path.abspath(current_app.config["UPLOAD_FOLDER"])
        uploaded_file = request.files["file"]

        if not uploaded_file:
            return response(400, "No file uploaded", 0, None)

        if not allowed_filename(uploaded_file.filename):
            return response(400, "Invalid file", 0, None)

        # Convert audio
        wav_file = os.path.join(
            upload_folder,
            secure_filename(uploaded_file.filename.replace(".mp3", ".wav")))
        try:
            song = AudioSegment.from_mp3(uploaded_file)
        except:
            print_exc()
            return response(500, "Unable to load file", 0, None)

        try:
            song.export(wav_file, format="wav")
        except:
            print_exc()
            return response(500, "Unable to transform file to wav", 0, None)

        #return response(202, "File saved to {}".format(wav_file), 0, None)
        # For testing, remove file again
        rm_file(wav_file)
        return response(202, "File OK", 0, None)
Пример #4
0
    def post(self):
        """POST method to create a new blueprint."""

        data = self.parser.parse_args()

        if BlueprintModel.find_by_image(data['image']):
            return response(
                400, None,
                f"Blueprint with image {data['image']} already exists.",
                None), 400

        blueprint = BlueprintModel(name=data['name'],
                                   description=data['description'],
                                   image=data['image'])

        try:
            blueprint.save_to_db()
        except:
            return response(
                500, None,
                f"An error occured while trying to update blueprint {data['name']}.",
                None), 500

        return response(201, f"Blueprint {data['name']} has been updated.",
                        None, blueprint.json()), 201
Пример #5
0
  def post(self, _id):
    """Shuts down a specific stack configurations

    Runs `docker-compose down`

    Args:
      _id (int): The stack ID of the stack to be shut down.

    """

    stack = StackModel.find_by_id(_id)

    if not stack:
      return response(404, None, f"Stack with ID {_id} does not exist.", None), 404      

    project_folder = stack.get_project_folder()

    # Check if folders exist
    if not path.exists(project_folder):
      return response(404, None, f"Project folder for stack {stack.name} doesn't exist.", None), 404

    try:
      cmd = subprocess.run(["docker-compose", "down"], check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=project_folder)
      return response(200, f"Stack {stack.name} has been shut down.", None, {'stdout': cmd.stdout.decode("utf-8")}), 200
    except subprocess.CalledProcessError as e:
      print_exc()
      return response(500, None, f"An error occured while trying to stop {stack.name}", {'stdout': e.stdout.decode("utf-8")}), 500
Пример #6
0
def get_photos():
    faceid = request.args['faceid']
    if _add_faceid(faceid):
        return response().error().message("该FaceId尚未注册").make()
    return response().succeed().message("FaceID("+str(faceid)+"),共有"+\
                str(redis.getPicNum(faceid))+"/"+str(app.config['MAX_UPLOAD_EACH_FACE'])+\
                    "张照片").setdata(_set_b_2_list_str(redis.getPics(faceid))).make()
Пример #7
0
def train_modal():
    try:
        print("Training KNN classifier...")
        start = perf_counter()
        train(app.config['UPLOAD_FOLDER'],model_save_path="trained_knn_model.clf")
        elapsed = (perf_counter() - start)
        print("Training complete!","time spend:",elapsed)
        return response().succeed().message("训练完毕!耗时:"+str(elapsed)+"秒").make()
    except:
        return response().error().message("训练失败").make()
Пример #8
0
def del_face():
    faceid = request.form['faceid']
    if _add_faceid(faceid):
        return response().error().message("该FaceId尚未注册").make()
    filenames = _set_b_2_list_str(redis.getPics(faceid))
    for filename in filenames:
        os.remove(_get_directory(faceid,filename))
    os.rmdir(_get_directory(faceid))
    redis.delFace(faceid)
    return response().succeed().message("删除成功,Face("+str(faceid)+")").make()
def identify(id, identity):
    cursor.execute("select identify from %s" % identity + " where id=%s",
                   (id, ))  # 动态创建数据表必须这样创建
    identify = cursor.fetchone()
    if identify == (None):
        return response(400, "id has not exist")
    cursor.execute("update %s " % identity + " set identify=1 where id=%s",
                   (id, ))
    db.commit()
    return response(200)
Пример #10
0
def recognize():
    if 'photo' not in request.files:
        return response().error().message("未上传").make()
    photo = request.files['photo']
    if photo and _is_allowed_file(photo.filename):
        if _is_human_face(photo):
            start = perf_counter()
            resl = predict(photo, model_path="trained_knn_model.clf")
            elapsed = (perf_counter() - start)
            return response().succeed().message("识别完毕!FaceId:"+resl[0][0]+"。耗时:"+str(elapsed)+"秒").setdata(resl).make()
    return response().error().message("识别失败").make()
Пример #11
0
def del_photos():
    faceid = request.form['faceid']
    if _add_faceid(faceid):
        return response().error().message("该FaceId尚未注册").make()
    filename_str = request.form['filenames']
    filenames = json.loads(filename_str)
    for filename in filenames:
        os.remove(_get_directory(faceid,filename))
        redis.delPic(faceid,filename)
    return response().succeed().message("删除成功,FaceID("+str(faceid)+"),现有"+\
                str(redis.getPicNum(faceid))+"/"+str(app.config['MAX_UPLOAD_EACH_FACE'])+\
                    "张照片").setdata(_set_b_2_list_str(redis.getPics(faceid))).make()
Пример #12
0
  def get(sef, _id):
    """GET method to retrieve a stack by ID."""

    try:
      stack = StackModel.find_by_id(_id)
    except:
      print_exc()
      return response(500, None, f"An error occured while trying to retrieve stack {stack.name}.", None), 500
    if stack:
      return response(200, f"Stack {stack.name} has been retrieved.", None, stack.json()), 200

    return response(404, None, f"Stack with id {_id} does not exist.", None), 404
Пример #13
0
def upload():
    faceid = request.form['faceid']
    if not _add_faceid(faceid): #faceid是否已注册
        if 'photos' in request.files: #是否上传了照片
            for photo in request.files.getlist('photos'): #遍历照片
                if _is_upto_limit(faceid):
                    break
                _save_photo(faceid,photo)
            return response().succeed().message("FaceID("+str(faceid)+"),添加成功,现有"+\
                str(redis.getPicNum(faceid))+"/"+str(app.config['MAX_UPLOAD_EACH_FACE'])+\
                    "张照片").setdata(_set_b_2_list_str(redis.getPics(faceid))).make()
        return response().succeed().message("请上传照片").make()
    return response().error().message("该FaceId尚未注册").make()
Пример #14
0
    def post(self):
        upload_folder = os.path.abspath(current_app.config["UPLOAD_FOLDER"])
        file_name = str(uuid.uuid4())
        file_path = os.path.join(upload_folder, file_name)

        # Accept binary file file
        try:
            with open(file_path, "wb") as wf:
                chunk_size = 4096
                while True:
                    chunk = request.stream.read(chunk_size)
                    if len(chunk) == 0:
                        break

                    wf.write(chunk)
        except:
            print_exc()
            rm_file(wav_file)
            return response(
                500, "Internal error occured while trying to upload file", 0,
                None)

        if not os.path.isfile(file_path) or os.path.getsize(file_path) <= 0:
            print("File {} doesn't exist".format(file_path))
            return response(400, "Uploaded file hasn't been saved", 0, None)
        else:
            print("File saved to {}, size: {}".format(
                file_path, os.path.getsize(file_path)))

        # Transform file into wav
        try:
            song = AudioSegment.from_mp3(file_path)
        except:
            print_exc()
            rm_file(file_path)
            return response(500, "Unable to load mp3 file", 0, None)
        wav_file = os.path.join(upload_folder, file_name + ".wav")
        try:
            song.export(wav_file, format="wav")
        except:
            print_exc()
            rm_file(file_path)
            return response(500, "Unable to transform file to wav", 0, None)

        rm_file(file_path)
        # return response(202, "File saved to {}".format(file_path), 0, None)

        # For testing, remove file again
        rm_file(wav_file)
        return response(202, "File OK", 0, None)
def a_register(id, password, email):
    cursor.execute("select * from administrator where id=%s", id)
    if cursor.fetchone() == (None):
        cursor.execute(
            "insert into administrator(id,password,email,identify) values(%s,%s,%s,%s)",
            (
                id,
                password,
                email,
                0,
            ))
        db.commit()
        return response(200)
    else:
        return response(400, "id has been used")
Пример #16
0
  def delete(self, _id):
    """DELETE method to delete service by ID."""    

    try:
      service = ServiceModel.find_by_id(_id)
    except:
      return response(500, None, f"An error occured while trying to delete service {service.name}.", None), 500

    if service:
      try:
        service.delete_from_db()
      except:
        return response(500, None, f"An error occured while trying delete service {data['name']}.", None), 500
      return response(200, f"Service {service.name} has been deleted.", None, None), 200

    return response(404, None, f"Service with id {_id} does not exist.", None), 404
Пример #17
0
def m_register(id, password, email, addr):
    cursor.execute("select * from merchant where id=%s", id)
    if cursor.fetchone() == (None):
        cursor.execute(
            "insert into merchant(id,password,email,identify,addr) values(%s,%s,%s,%s,%s)",
            (
                id,
                password,
                email,
                0,
                addr,
            ))
        db.commit()
        return response(200)
    else:
        return response(400, "id has been used")
Пример #18
0
def log_in():
    if request.cookies.get("id"):
        return response(403, "you id had login")
    data = request.get_json()
    id = data['id']
    password = data['password']
    status = request.args.get('status')
    return login(id, password, status)
Пример #19
0
  def delete(self, _id):
    stack = StackModel.find_by_id(_id)

    if not stack:
      return response(404, None, f"Stack with ID {_id} does not exist.", None), 404

    for service in stack.services:
      container = get_container(f"{stack.name}_{service.name}")

      if container and container.status in ['running', 'exited']:
        try:
          container.remove(force=True)
        except:
          print_exc()
          return response(500, None, f"An error occured while trying to remove container of service {service.name}.", None), 500

    return response(200, f"Containers for stack {stack.name} have been removed successfully.", None, None), 200
Пример #20
0
def check_commodity(merchant_id):
    """
    查找这个商家的所有商品
    """

    cursor.execute("select * from commodity where merchant_id=%s", merchant_id)
    commodity = []
    for t in cursor.fetchall():
        commodity.append(t)
    return response(200, commodity)
Пример #21
0
  def get(self, _id):
    """Shows information about a stack

    Args:
      _id (int): The stack ID.

    """
    stack = StackModel.find_by_id(_id)

    if not stack:
      return response(404, None, f"Stack with ID {_id} does not exist.", None), 404      

    # Check if folders exist
    project_folder = stack.get_project_folder()
    if not path.exists(project_folder):
      return response(404, None, f"Project folder for stack {stack.name} doesn't exist.", None), 404    

    # Loop through assigned services and add container to list it's running
    if stack.services:
      container_list = []
      for service in stack.services:
        container = get_container(f"{stack.name}_{service.name}")
        if container:
          container_list.append(container)
    else:
      return response(400, f"Stack {stack.name} has no services assigned.", None, None), 400

    # If containers are running, output information
    if len(container_list) > 0:
      info = {
        'id': stack.id,
        'name': stack.name,
        'subdomain': stack.subdomain,
        'port': stack.proxy_port,
        'services': [container_data(x) for x in container_list]
      }
      return response(200, f"Data for services in stack {stack.name} has been retrieved.", None, info), 200

    # Else output that nothing is up
    else:
      return response(200, f"No service is in running or exited status.", None, None), 200
def no_identity():
    data = []
    cursor.execute("select * from client where identify=0")
    for i in cursor.fetchall():
        data.append(i)
    cursor.execute("select * from merchant where identify=0")
    for i in cursor.fetchall():
        data.append(i)
    cursor.execute("select * from administrator where identify=0")
    for i in cursor.fetchall():
        data.append(i)
    return response(200, data)
Пример #23
0
    def post(self):
        """POST method to register a user."""

        data = UserRegister.parser.parse_args()

        if UserModel.find_by_username(data['username']):
            return response(400, None,
                            f"User {data['username']} already exists.",
                            None), 400

        user = UserModel(**data)
        try:
            user.save_to_db()
        except:
            return response(
                500, None,
                f"An error occured while trying to create user {data['username']}.",
                None), 500

        return response(201, f"User {data['username']} has been created.",
                        None, None), 201
Пример #24
0
  def post(self):
    """POST method to create a new service."""

    data = self.parser.parse_args()

    if ServiceModel.find_by_name(data['name']):
      return response(400, None, f"Service with name {data['name']} already exists.", None), 400

    args = self.check_args(data)
    if args['code'] is not 200:
      return response(args['code'], None, args['error'], None), args['code']

    volumes = ServiceModel.join_volume_string(data)
    env = ServiceModel.join_env_string(data)
    exposed_ports = ServiceModel.join_port_string(data['exposed_ports'])
    mapped_ports = ServiceModel.join_port_string(data['mapped_ports'])

    service = ServiceModel(name = data['name'],
                           blueprint_id = data['blueprint'],
                           description = data['description'],
                           exposed_ports = exposed_ports,
                           mapped_ports = mapped_ports,
                           volumes = volumes,
                           restart = data['restart'],
                           env = env)

    # Add stack to service table
    if data['stacks'] and data['stacks'] != [None]:
      for x in data['stacks']:
        stack = StackModel.find_by_id(x)
        service.stacks.append(stack)

    try:
      service.save_to_db()
      service.ip = service.get_ip(service.id)
      service.save_to_db()
    except:
      return response(500, None, f"An error occured while trying to update service {data['name']}.", None), 500

    return response(201, f"Service {data['name']} has been updated.", None, service.json()), 201
Пример #25
0
def modify_commodity(id, price, clss, photo, commodity_rest, merchant_id):
    """
    修改商品信息
    这里的商家id不变,因为商品永远属于当前商家
    """
    cursor.execute(
        "select price from commodity where id=%s and merchant_id=%s", (
            id,
            merchant_id,
        ))
    pri = cursor.fetchone()
    p = pri[0]
    if p > price:
        cursor.execute("select c_id from favourites where m_id=%s",
                       (id, ))  # 进入该用户的消息盒子,在下一次打开该用户是发送消息给这个用户
        mem = cursor.fetchall()
        for i in mem:  # 进入每个用户的消息盒子
            m = i[0]
            cursor.execute(
                "insert into message%s(message) values('You favourite thing price reduced')"
                % m)  # mysql语句中不能乱加单引号
    cursor.execute("select * from commodity where id=%s and merchant_id=%s", (
        id,
        merchant_id,
    ))
    if cursor.fetchone() == (None):  # 判断id是否存在
        return response(400, "no this modity")
    f1 = open('/home/oldli/weblearning/flask/project/mall/photo' + id + '.jpg',
              'w')  # 以wb形式打开若文件不存在则会自动生成,原来的数据会被抹去重新写
    f1.write(photo)
    cursor.execute(
        "update commodity set price=%s,cls=%s,commodity_rest=%s where id=%s", (
            price,
            clss,
            commodity_rest,
            id,
        ))
    db.commit()
    return response(200)
Пример #26
0
  def delete(self, _id):
    """DELETE method to delete a stack by ID."""

    try:
      stack = StackModel.find_by_id(_id)
    except:
      return response(500, None, f"An error occured while trying to save stack {stack.name}.", None), 500

    # Check if services are running first
    for service in stack.services:
      if container_is_up(f"{stack.name}_{service.name}"):
        return response(400, None, f"Stack {stack.name} has services running or in exited status. Please remove them first.", None), 400

    if stack:
      try:
        stack.delete_from_db()
      except:
        print_exc()
        return response(500, None, f"An error occured while trying to delete stack {stack.name}.", None), 500
        
      return response(200, f"Stack {stack.name} has been deleted.", None, None), 200

    return response(404, None, f"Stack with id {_id} does not exist.", None), 404
Пример #27
0
def modify_merchant(id, password, email, addr):
    """
    id作为唯一标识符,在这里不能被修改
    这里不会有用户不存在的情况,因为必须先登录才可能修改资料
    """
    cursor.execute(
        "update merchant set password=%s,email=%s,addr=%s where id=%s", (
            password,
            email,
            addr,
            id,
        ))
    db.commit()
    return response(200)
Пример #28
0
def de_commodity(id, merchant_id):
    """ 
    商家下架商品
    用户收藏商品下架提醒
    """

    cursor.execute("select * from commodity where id=%s and merchant_id=%s", (
        id,
        merchant_id,
    ))
    if cursor.fetchone() != (None):
        cursor.execute("delete from commodity where id=%s and merchant_id=%s",
                       (id, merchant_id))
        db.commit()
        cursor.execute("select c_id from favourites where m_id=%s",
                       id)  # 进入该用户的消息盒子,在下一次打开该用户是发送消息给这个用户
        for i in cursor.fetchall():  # 进入每个用户的消息盒子
            cursor.execute(
                "insert into message%s(message) values('You favourite has obtained')"
                % i[0])
        return response(200)
    else:
        return response(400, "This commodity has not exist")
Пример #29
0
def login(id, pwd, status):
    """
    client 成功只验证了未认证的失败和验证了的成功这两个示例
    """
    if status == '1':  # 登录时三种用户分开登录
        cursor.execute("select identify from client where id=%s", id)
        now_status = cursor.fetchone()
        if now_status[0] == 0:  # 判断是否被认证通过
            return response(400, "have not been identify")
        else:
            cursor.execute("select password from client where id=%s", id)
    elif status == '2':
        cursor.execute("select identify from merchant where id=%s", id)
        now_status = cursor.fetchone()
        if now_status[0] == 0:
            return response(400, "have not been identify")
        else:
            cursor.execute("select password from merchant where id=%s", id)
    elif status == '3':
        cursor.execute("select identify from administrator where id=%s", id)
        now_status = cursor.fetchone()
        if now_status[0] == 0:
            return response(400, "have not been identify")
        else:
            cursor.execute("select password from administrator where id=%s",
                           id)
    accurate_pwd = cursor.fetchone()
    if accurate_pwd != ():
        if check_password_hash(accurate_pwd[0], pwd):
            rsp = make_response('{"status":"200"}')
            rsp.set_cookie('id', id)  # 返回登录者id
            return rsp
        else:
            return response(401, "password_wrong")
    else:
        return response(402, "id_wrong")
Пример #30
0
def add_commodity(id, price, clss, photo, commodity_rest, merchant_id):
    cursor.execute("select * from commodity where id=%s and merchant_id=%s", (
        id,
        merchant_id,
    ))
    if cursor.fetchone() != (None):  # 判断id是否已经存在
        return response(400, "id has been used")
    f1 = open('/home/oldli/weblearning/flask/project/mall/photo/' + id +
              '.jpg', 'w')  # 以wb形式打开若文件不存在则会自动生成
    f1.write(photo)
    f1.close()
    photo_path = '127.0.0.1/' + id + '.jpg'  # 从前端传来文件的数据,存储在本地,前段再次调用时用nginx静态文件来获取
    cursor.execute(
        "insert into commodity(id,price,cls,photo,commodity_rest,merchant_id) values(%s,%s,%s,%s,%s,%s)",
        (
            id,
            price,
            clss,
            photo_path,
            commodity_rest,
            merchant_id,
        ))
    db.commit()
    return response(200)