コード例 #1
0
def upload_summary():
    info_form = ChangeinfoForm()
    passwd_form = EditPasswordForm()
    summary_form = SummaryForm()
    pay_form = PayForm()
    if request.method == 'POST':
        if 'summary' not in request.files or request.files[
                'summary'].filename == '':
            flash(u'当前没有选取到您上传的摘要', 'danger')
            return redirect(url_for('users.update'))
        file = request.files['summary']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            saveFilename = '_'.join([current_user.username, filename])
            current_user.update(filename=saveFilename)
            file.save(os.path.join(Config.UPLOAD_FOLDER, saveFilename))
            flash(u'摘要上传成功', 'success')
            redirect(url_for('users.members'))
        else:
            flash(u'上传文件格式不正确', 'danger')
            redirect(url_for('users.update'))
    return render_template('user/update.html',
                           info_form=info_form,
                           passwd_form=passwd_form,
                           summary_form=summary_form,
                           pay_form=pay_form)
コード例 #2
0
ファイル: views.py プロジェクト: kyle8285/pic-up
def upload_file():
	if request.method == 'POST':
		file = request.files['file']
		if file and allowed_file(file.filename):
			print(file)
			# Image object can be used to open a file-like object
			# the object must implement read(), seek() and tell() 
			# methods and be opened in binary mode
			image = Image.open(file)

			byte_io = BytesIO()

			ext = file.mimetype.split('/')[1]

			image.save(byte_io, ext)

			# move to the beginning of the file
			byte_io.seek(0)

			return send_file(byte_io, mimetype=file.mimetype)
		# else:
		# 	data = {"message": "Oops, there was an error!"}
		# 	return render_template('upload.html', message=data.message)

		message = 'Oops! We couldn\'t load that file. Please make sure it\'s a proper image file.'
		return render_template('index.html', message=message)

	return render_template('index.html')
コード例 #3
0
ファイル: routes.py プロジェクト: Ecvelnter/blog-2
def upload():
    f = request.files.get('upload')
    if not allowed_file(f.filename):
        return upload_fail('Image only!')

    f.filename = time.strftime('%Y%m%d%H%M%S',time.localtime()) + '_' + f.filename
    f.save(os.path.join(current_app.config['UPLOADED_PATH'],f.filename))
    url = url_for('main.uploaded_files', filename=f.filename)
    return upload_success(url,f.filename)
コード例 #4
0
    def upload_profile_picture(self):
        if request.method == 'POST':
            # check if the post request has the file part
            if 'file' not in request.files:
                return http_error("No file part selected", 400)
            file = request.files['file']
            # if user does not select file, browser also
            # submit an empty part without filename
            if file.filename == '':
                return http_error("No selected file!", 400)

            if file and allowed_file(file.filename):
                # Pass through secure filename
                filename = secure_filename(file.filename)
                # Extract the filename and the file extention
                # file_name, file_ext = os.path.splitext(filename)
                _, file_ext = os.path.splitext(filename)
                # Create a new file_name and concatnate with the ext
                new_file_name = str(uuid.uuid4())
                new_file_name = "{}{}".format(new_file_name, file_ext)

                file.save(os.path.join(UPLOAD_FOLDER, new_file_name))

                # Save the Profile Picture Url in Profile table
                user = auth().get('user')
                profile = user.profile
                # Create the Profile Url
                profile_picture_url = "{}{}{}".format(API_URL,
                                                      '/profile/picture/',
                                                      new_file_name)
                profile.profile_picture_url = profile_picture_url

                # Then commit the session
                db.session.commit()
                # Return Json Response of the profile to the client
                profile_result = self.profile_schema.dump({
                    "name":
                    profile.name,
                    "profile_picture_url":
                    profile.profile_picture_url,
                    "profile_created_at":
                    profile.profile_created_at,
                    "profile_public_id":
                    profile.profile_public_id,
                    "profile_updated_at":
                    profile.profile_updated_at,
                    "email":
                    user.email,
                    "username":
                    user.username,
                    "is_admin":
                    user.is_admin,
                    "is_active":
                    user.is_active
                })

                return self.profile_schema.jsonify(profile_result)
コード例 #5
0
ファイル: routes.py プロジェクト: wtraceback/Blog
def upload_image():
    f = request.files.get('upload')

    if not allowed_file(f.filename):
        return upload_fail('Image only!')

    path = current_app.config['BLOG_UPLOAD_PATH']
    f.save(os.path.join(path, f.filename))
    url = url_for('admin.get_image', filename=f.filename)
    return upload_success(url=url)
コード例 #6
0
def process(data=None, via_api=False):
    """
    Start the generation process when the form is submitted
    :return:
    """
    if not data:
        data = request.form
    email = data.get('email', None)
    data_source = data.get('data-source', None)
    build_type = data.get('build-type', None)
    is_auth_enabled = data.get('is-auth-enabled', 'false') == 'true'
    theme_colors = json.loads(data.get('colors', None))

    if not email or not data_source or data_source not in VALID_DATA_SOURCES or not validators.email(
            email):
        return jsonify(status='error', message='invalid data'), 400

    payload = {'creator_email': email, 'is_auth_enabled': is_auth_enabled}

    identifier = str(uuid.uuid4())

    if data_source == 'api_endpoint':
        api_endpoint = data.get('api-endpoint', None)
        if not api_endpoint or not validators.url(api_endpoint):
            return jsonify(status='error', message='invalid endpoint url'), 400
        payload['endpoint_url'] = api_endpoint
    elif data_source == 'json_upload':
        if 'json-upload' not in request.files:
            return jsonify(
                status='error',
                message='data file is required for the selected source'), 400
        uploaded_file = request.files['json-upload']
        if uploaded_file.filename == '':
            return jsonify(
                status='error',
                message='data file is required for the selected source'), 400
        if uploaded_file and allowed_file(uploaded_file.filename, ['zip']):
            filename = secure_filename(identifier)
            file_save_location = os.path.join(app.config['UPLOAD_DIR'],
                                              filename)
            uploaded_file.save(file_save_location)
            payload['zip_file'] = file_save_location

    from app.tasks import generate_app_task  # A Local import to avoid circular import
    task = generate_app_task.delay(config=app.config,
                                   payload=payload,
                                   via_api=via_api,
                                   identifier=identifier,
                                   build_type=build_type,
                                   theme_colors=theme_colors)
    return jsonify(status='ok',
                   identifier=identifier,
                   started_at=datetime.datetime.now(),
                   task_id=task.id)
コード例 #7
0
def UserAvatar(username):
    if User.query.filter_by(username=username) is None:
        return no_person()
    if not os.path.exists(UPLOAD_PATH):
        os.makedirs(UPLOAD_PATH)
    file = request.files['file']
    filename = file.filename
    if allowed_file(filename):
        new_filename = random_filename(filename)
        file.save(os.path.join(UPLOAD_PATH, new_filename))
        user = User.query.filter_by(username=username).first()
        user.user_avatar = new_filename
        db.session.commit()
        return jsonify({"status": 0, "message": ""})
    else:
        return data_wrong(message="File type not allowed")
コード例 #8
0
ファイル: controllers.py プロジェクト: jounile/nollanet
def savefile():
    if request.method == 'POST':
        blob_service = utils.get_azure_blob_service()
        images_container = 'images'
        video_container = 'videos'
        if request and request.files and request.files.get('file'):
            file_to_upload = request.files.get('file')
            filename = file_to_upload.filename
        path = ''
        if filename == '':
            return "error.png"
        if file_to_upload and utils.allowed_file(filename):
            filename = datetime.datetime.now().strftime(
                "%d-%m-%Y_%I-%M-%S") + "_" + filename
            filename = secure_filename(filename)

            # Create Blob from stream
            try:
                if utils.isImage(filename):
                    blob_service.create_blob_from_stream(
                        images_container, filename, file_to_upload)
                    path = 'images/' + filename
                    flash("Image " + filename + " was uploaded successfully")
                if utils.isVideo(filename):
                    blob_service.create_blob_from_stream(
                        video_container, filename, file_to_upload)
                    path = 'videos/' + filename
                    flash("Video " + filename + " was uploaded successfully")
            except:
                flash("Something went wrong while uploading the files %s" %
                      filename)
                pass

            # Create a record in database
            upload = Uploads(user_id=session['user_id'],
                             create_time=datetime.datetime.now(),
                             path=path)
            db.session.add(upload)
            db.session.commit()
            #print("Upload was inserted to database by user " + session['username'])

            return filename
        else:
            flash("File type is not allowed")
    return None
コード例 #9
0
def process(data=None, via_api=False):
    """
    Start the generation process when the form is submitted
    :return:
    """
    if not data:
        data = request.form
    email = data.get('email', None)
    data_source = data.get('data-source', None)

    if not email or not data_source or data_source not in VALID_DATA_SOURCES or not validators.email(email):
        return jsonify(status='error', message='invalid data'), 400

    payload = {
        'creator_email': email
    }

    identifier = str(uuid.uuid4())

    if data_source == 'api_endpoint':
        api_endpoint = data.get('api-endpoint', None)
        if not api_endpoint or not validators.url(api_endpoint):
            return jsonify(status='error', message='invalid endpoint url'), 400
        payload['endpoint_url'] = api_endpoint
    elif data_source == 'json_upload':
        if 'json-upload' not in request.files:
            return jsonify(status='error', message='data file is required for the selected source'), 400
        uploaded_file = request.files['json-upload']
        if uploaded_file.filename == '':
            return jsonify(status='error', message='data file is required for the selected source'), 400
        if uploaded_file and allowed_file(uploaded_file.filename, ['zip']):
            filename = secure_filename(identifier)
            file_save_location = os.path.join(app.config['UPLOAD_DIR'], filename)
            uploaded_file.save(file_save_location)
            payload['zip_file'] = file_save_location

    from app.tasks import generate_app_task  # A Local import to avoid circular import
    task = generate_app_task.delay(config=app.config, payload=payload, via_api=via_api, identifier=identifier)
    return jsonify(status='ok', identifier=identifier, started_at=datetime.datetime.now(), task_id=task.id)
コード例 #10
0
ファイル: app.py プロジェクト: mvshvets/openSpace
    def post(self):
        """
        Загрузка фотографии
        """

        args = upload_parser.parse_args()
        uploaded_file = args['file']

        if not allowed_file(uploaded_file.filename):
            return {
                "message": {
                    "Можно загрузить только файлы в формате {}".format(
                        ALLOWED_EXTENSIONS)
                }
            }

        if uploaded_file:
            filename = secure_filename(uploaded_file.filename)

            # магия с file

            return {"message": "Фото успешно загружено"}
コード例 #11
0
ファイル: path.py プロジェクト: Qqlick/robot_navigation
def upload_file():
    if "file" not in request.files:
        resp = jsonify({"message": "No file part in the request"})
        resp.status_code = 400
        return resp
    file = request.files["file"]
    if file.filename == "":
        resp = jsonify({"message": "No file selected for uploading"})
        resp.status_code = 400
        return resp
    if file and allowed_file(file.filename):
        locs_json = json.load(file)
        validate_data(locs_json, "paths")
        Path.batch_save(locs_json)

        resp = jsonify({"message": "File successfully uploaded"})
        resp.status_code = 201
        return resp

    else:
        resp = jsonify({"message": "Allowed file types are json, yml"})
        resp.status_code = 400
    return resp
コード例 #12
0
def index():
    if request.method == 'POST':
        if 'file1' not in request.files:
            flash('No file part')
            return redirect(url_for('home.index'))

        num = random.randint(1, 3)
        file = request.files[f'file{num}']
        if file.filename == '':
            flash('No image selected for uploading')
            return redirect(url_for('home.index'))
        if file and allowed_file(file.filename):
            filename = file.filename
            file.save(
                os.path.join(current_app.config['UPLOAD_FOLDER'], filename))
            #print('upload_image filename: ' + filename)
            flash('You should wear this!')
            return render_template('home/index.html', filename=filename)
        else:
            flash('Allowed image types are -> png, jpg, jpeg, gif')
            return redirect(url_for('home.index'))

    return render_template('home/index.html')
コード例 #13
0
ファイル: main.py プロジェクト: alanfanh/lab-web
def upload(name):
    print("request.files=", request.files)
    depot = Depot.query.filter_by(name=name).first()
    template_id = depot.template_id
    status_dict = {"在库": "1", "借出": "2"}
    if request.method == 'POST' and 'file' in request.files:
        f = request.files.get('file')
        print("f=", f)
        filename = rename_file(f.filename)
        print("filename=", filename)
        if allowed_file(f.filename):
            if not os.path.exists(current_app.config['UPLOAD_PATH']):
                os.mkdir(current_app.config['UPLOAD_PATH'])
            path = os.path.join(current_app.config['UPLOAD_PATH'], filename)
            f.save(path)
        else:
            flash('失败:上传文件格式错误,请上传文件后缀为.xls和.xlsx的文件', 'err')
            return redirect(url_for('main.show', name=depot.name))
        datas = read_excel(path)
        print("*******datas=", datas)
        #判断表格格式是否正确
        if template_id == 1:
            head = [
                '资产编号', '品牌', '规格型号', '现存数量', '储位', '入库时间', '状态', '借机人',
                '借机邮箱', '借机时间', '借机数量', '预计归还时间', '备注', '盘盈/盘亏'
            ]
            if not checkHead(head, datas[0]):
                flash("失败:上传文件表头信息错误,正确的表头信息为%s" % head, 'err')
                return redirect(url_for('main.show', name=depot.name))
            #检查内容是否符合格式
            datas.remove(datas[0])
            for data in datas:
                if checkEmpty(data['资产编号']) or not checkType(data['资产编号']):
                    flash('失败:资产编号不能为空,且只能输入数字、字母和下划线,资产编号=%s' % data['资产编号'],
                          'err')
                    return redirect(url_for('main.show', name=depot.name))
                if checkEmpty(data['品牌']):
                    flash('失败:品牌不能为空,品牌=%s' % data['品牌'], 'err')
                    return redirect(url_for('main.show', name=depot.name))
                if checkEmpty(data['规格型号']):
                    flash('失败:规格型号不能为空,规格型号=%s' % data['规格型号'], 'err')
                    return redirect(url_for('main.show', name=depot.name))
                if checkEmpty(data['现存数量']) or not checkInt(data['现存数量']):
                    flash('失败:现存数量不能为空,且只能整数,数量=%s' % data['现存数量'], 'err')
                    return redirect(url_for('main.show', name=depot.name))
                if checkEmpty(data['储位']) or not checkType2(data['储位']):
                    flash('失败:储位不能为空,且只能输入数字、字母、中文和下划线,储位=%s' % data['储位'],
                          'err')
                    return redirect(url_for('main.show', name=depot.name))
                if checkEmpty(data['入库时间']) or not checkDate(data['入库时间']):
                    flash("失败:入库时间格式为年-月-日或年/月/日,入库时间=%s" % data['入库时间'],
                          'err')
                    return redirect(url_for('main.show', name=depot.name))
                kwargs = {
                    'name': depot.name,
                    'assetnumber': data['资产编号'],
                    'product_name': data['品牌'],
                    'model_name': data['规格型号'],
                    'numbers': data['现存数量'],
                    'position': data['储位'],
                    'entertime': data['入库时间'],
                    'status': status_dict[data['状态']],
                    'remark': data['备注'],
                    'profit_loss': data['盘盈/盘亏']
                }
                if status_dict[data['状态']] == '1':
                    if not checkEmpty(data['借机人']):
                        flash('失败:在库时借机人必须为空,借机人=%s' % data['借机人'], 'err')
                        return redirect(url_for('main.show', name=depot.name))
                    if not checkEmpty(data['借机邮箱']):
                        flash('失败:在库时借机邮箱必须为空,借机邮箱=%s' % data['借机邮箱'], 'err')
                        return redirect(url_for('main.show', name=depot.name))
                    if not checkEmpty(data['借机数量']):
                        flash('失败:在库时借机数量必须为空,借机数量=%s' % data['借机数量'], 'err')
                        return redirect(url_for('main.show', name=depot.name))
                elif status_dict[data['状态']] == '2':
                    if checkEmpty(data['借机人']):
                        flash('失败:借机人不能为空,借机人=%s' % data['借机人'], 'err')
                        return redirect(url_for('main.show', name=depot.name))
                    if checkEmpty(
                            data['借机邮箱']) or not checkEmail(data['借机邮箱']):
                        flash('失败:借机邮箱不能为空,且格式符合邮箱要求,借机邮箱=%s' % data['借机邮箱'],
                              'err')
                        return redirect(url_for('main.show', name=depot.name))
                    if checkEmpty(data['借机数量']) or not checkInt(data['借机数量']):
                        flash('失败:借机数量不能为空,且只能输入整数,借机数量=%s' % data['借机数量'],
                              'err')
                        return redirect(url_for('main.show', name=depot.name))
                    if checkEmpty(data['借机时间']) or not checkDate(data['借机时间']):
                        flash("失败:借机时间格式为年-月-日或年/月/日,借机时间=%s" % data['借机时间'],
                              'err')
                        return redirect(url_for('main.show', name=depot.name))
                    if checkEmpty(
                            data['预计归还时间']) or not checkDate(data['预计归还时间']):
                        flash(
                            "失败:预计归还时间格式为年-月-日或年/月/日,预计归还时间=%s" %
                            data['预计归还时间'], 'err')
                        return redirect(url_for('main.show', name=depot.name))
                    userinfo = {
                        'username': data['借机人'],
                        'usermail': data['借机邮箱'],
                        'lend_time': data['借机时间'],
                        'back_time': data['预计归还时间'],
                        'lend_numbers': data['借机数量']
                    }
                    kwargs.update(userinfo)
                cmp = T1(**kwargs)
                if T1.query.filter_by(assetnumber=data['资产编号']).count() > 0:
                    flash('失败:编号为%s的资产已存在' % data['资产编号'], 'err')
                    return redirect(url_for('main.show', name=depot.name))
                db.session.add(cmp)
            db.session.commit()
            flash('上传成功', 'success')
            return redirect(url_for('main.show', name=depot.name))
        elif template_id == 2:
            head = [
                '资产编号', '品牌', '规格型号', '数量(套/个)', '责任组/人', '储位', '上次校准时间',
                '复校时间', '状态', '借用人', '借用邮箱', '借用时间', '预计归还时间', '备注', '盘盈/盘亏'
            ]
            if not checkHead(head, datas[0]):
                flash("失败:上传文件表头信息错误,正确的表头信息为%s" % head, 'err')
                return redirect(url_for('main.show', name=depot.name))
            #检查内容是否符合格式
            datas.remove(datas[0])
            for data in datas:
                if checkEmpty(data['资产编号']) or not checkType(data['资产编号']):
                    flash('失败:资产编号不能为空,且只能输入数字、字母和下划线,资产编号=%s' % data['资产编号'],
                          'err')
                    return redirect(url_for('main.show', name=depot.name))
                if checkEmpty(data['品牌']):
                    flash('失败:品牌不能为空=%s' % data['品牌'], 'err')
                    return redirect(url_for('main.show', name=depot.name))
                if checkEmpty(data['规格型号']):
                    flash('失败:规格型号不能为空=%s' % data['规格型号'], 'err')
                    return redirect(url_for('main.show', name=depot.name))
                if checkEmpty(
                        data['数量(套/个)']) or not checkInt(data['数量(套/个)']):
                    flash('失败:数量不能为空,且只能是整数,数量(套/个)=%s' % data['现存数量(套/个)'],
                          'err')
                    return redirect(url_for('main.show', name=depot.name))
                if checkEmpty(data['责任组/人']):
                    flash('失败:责任组/人不能为空')
                    return redirect(url_for('main.show', name=depot.name))
                if checkEmpty(data['储位']) or not checkType2(data['储位']):
                    flash('失败:储位不能为空,且只能输入数字、字母、中文和下划线,储位=%s' % data['储位'],
                          'err')
                    return redirect(url_for('main.show', name=depot.name))
                if checkEmpty(data['上次校准时间']) or not checkDate(data['上次校准时间']):
                    flash('失败:上次校准时间格式为年-月-日或年/月/日,上次校准时间=%s' % data['上次校准时间'],
                          'err')
                    return redirect(url_for('main.show', name=depot.name))
                if checkEmpty(data['复校时间']) or not checkDate(data['复校时间']):
                    flash('失败:复校时间格式为年-月-日或年/月/日,复校时间=%s' % data['复校时间'],
                          'err')
                    return redirect(url_for('main.show', name=depot.name))
                if checkCompareDate(data['上次校准时间'], data['复校时间']):
                    flash(
                        '失败:复校时间不能小于上次校准时间,上次校准时间=%s,复校时间=%s' %
                        (data['上次校准时间'], data['复校时间']), 'err')
                    return redirect(url_for('main.show', name=depot.name))
                kwargs = {
                    'name': depot.name,
                    'assetnumber': data['资产编号'],
                    'product_name': data['品牌'],
                    'model_name': data['规格型号'],
                    'numbers': data['数量(套/个)'],
                    'owner': data['责任组/人'],
                    'position': data['储位'],
                    'calibratetime': data['上次校准时间'],
                    'resumptiontime': data['复校时间'],
                    'status': status_dict[data['状态']],
                    'remark': data['备注'],
                    'profit_loss': data['盘盈/盘亏']
                }
                if status_dict[data['状态']] == '1':
                    if not checkEmpty(data['借用人']):
                        flash('失败:在库时借用人必须为空,借用人=%s' % data['借用人'], 'err')
                        return redirect(url_for('main.show', name=depot.name))
                    if not checkEmpty(data['借用邮箱']):
                        flash('失败:在库时借用邮箱必须为空,借用邮箱=%s' % data['借用邮箱'], 'err')
                        return redirect(url_for('main.show', name=depot.name))
                elif status_dict[data['状态']] == '2':
                    if checkEmpty(data['借用人']):
                        flash('失败:借用人不能为空,借用人=%s' % data['借用人'], 'err')
                        return redirect(url_for('main.show', name=depot.name))
                    if checkEmpty(
                            data['借用邮箱']) or not checkEmail(data['借用邮箱']):
                        flash('失败:借用邮箱不能为空,且格式符合邮箱要求,借用邮箱=%s' % data['借用邮箱'],
                              'err')
                        return redirect(url_for('main.show', name=depot.name))
                    if checkEmpty(data['借用时间']) or not checkDate(data['借用时间']):
                        flash('失败:借用时间格式为年-月-日或年/月/日,借用时间=%s' % data['借用时间'],
                              'err')
                        return redirect(url_for('main.show', name=depot.name))
                    if checkEmpty(
                            data['预计归还时间']) or not checkDate(data['预计归还时间']):
                        flash(
                            '失败:预计归还时间格式为年-月-日或年/月/日,预计归还时间=%s' %
                            data['预计归还时间'], 'err')
                        return redirect(url_for('main.show', name=depot.name))
                    if checkCompareDate(data['借用时间'], data['预计归还时间']):
                        flash(
                            '失败:预计归还时间不能小于借机时间,借用时间=%s,预计归还时间=%s' %
                            (data['借用时间'], data['预计归还时间']), 'err')
                        return redirect(url_for('main.show', name=depot.name))
                    userinfo = {
                        'username': data['借用人'],
                        'usermail': data['借用邮箱'],
                        'lend_time': data['借用时间'],
                        'back_time': data['预计归还时间']
                    }
                    kwargs.update(userinfo)
                cmp = T2(**kwargs)
                if T2.query.filter_by(assetnumber=data['资产编号']).count() > 0:
                    flash('失败:编号为%s的资产已存在' % data['资产编号'], 'err')
                    return redirect(url_for('main.show', name=depot.name))
                db.session.add(cmp)
            db.session.commit()
            flash('上传成功', 'success')
            return redirect(url_for('main.show', name=depot.name))
        elif template_id == 3:
            head = [
                '资产编号', '品牌', '规格型号', '数量(套/个)', '部门', '组别', '储位', '上次校准时间',
                '复校时间', '状态', '借用人', '借用邮箱', '借用数量', '借用时间', '备注', '盘盈/盘亏'
            ]
            if not checkHead(head, datas[0]):
                flash("失败:上传文件表头信息错误,正确的表头信息为%s" % head, 'err')
                return redirect(url_for('main.show', name=depot.name))
            #检查内容是否符合格式
            datas.remove(datas[0])
            for data in datas:
                if T3.query.filter_by(assetnumber=data['资产编号']).count() > 0:
                    flash('失败:资产编号已存在', 'err')
                    return redirect(url_for('main.show', name=depot.name))
                if checkEmpty(data['资产编号']) or not checkType(data['资产编号']):
                    flash('失败:资产编号不能为空,且只能输入数字、字母和下划线,资产编号=%s' % data['资产编号'],
                          'err')
                    return redirect(url_for('main.show', name=depot.name))
                if checkEmpty(data['品牌']):
                    flash('失败:品牌不能为空=%s' % data['品牌'], 'err')
                    return redirect(url_for('main.show', name=depot.name))
                if checkEmpty(data['规格型号']):
                    flash('失败:规格型号不能为空=%s' % data['规格型号'], 'err')
                    return redirect(url_for('main.show', name=depot.name))
                if checkEmpty(
                        data['数量(套/个)']) or not checkInt(data['数量(套/个)']):
                    flash('失败:数量不能为空,且只能是整数,数量(套/个)=%s' % data['数量(套/个)'],
                          'err')
                    return redirect(url_for('main.show', name=depot.name))
                if checkEmpty(data['部门']):
                    flash('失败:部门不能为空,部门=%s' % data['部门'], 'err')
                    return redirect(url_for('main.show', name=depot.name))
                if checkEmpty(data['组别']) or not checkType2(data['组别']):
                    flash('失败:组别不能为空,且只能输入数字、字母、下划线和中文,组别=%s' % data['组别'],
                          'err')
                    return redirect(url_for('main.show', name=depot.name))
                if checkEmpty(data['储位']) or not checkType2(data['储位']):
                    flash('失败:储位不能为空,且只能输入数字、字母、中文和下划线,储位=%s' % data['储位'],
                          'err')
                    return redirect(url_for('main.show', name=depot.name))
                if checkEmpty(data['上次校准时间']) or not checkDate(data['上次校准时间']):
                    flash('失败:上次校准时间格式为年-月-日或年/月/日,上次校准时间=%s' % data['上次校准时间'],
                          'err')
                    return redirect(url_for('main.show', name=depot.name))
                if checkEmpty(data['复校时间']) or not checkDate(data['复校时间']):
                    flash('失败:复校时间格式为年-月-日或年/月/日,复校时间=%s' % data['复校时间'],
                          'err')
                    return redirect(url_for('main.show', name=depot.name))
                if checkCompareDate(data['上次校准时间'], data['复校时间']):
                    flash(
                        '失败:复校时间不能小于上次校准时间,上次校准时间=%s,复校时间=%s' %
                        (data['上次校准时间'], data['复校时间']), 'err')
                    return redirect(url_for('main.show', name=depot.name))
                kwargs = {
                    'name': depot.name,
                    'assetnumber': data['资产编号'],
                    'product_name': data['品牌'],
                    'model_name': data['规格型号'],
                    'numbers': data['数量(套/个)'],
                    'department': data['部门'],
                    'owner': data['组别'],
                    'position': data['储位'],
                    'calibratetime': data['上次校准时间'],
                    'resumptiontime': data['复校时间'],
                    'status': status_dict[data['状态']],
                    'remark': data['备注'],
                    'profit_loss': data['盘盈/盘亏']
                }
                if status_dict[data['状态']] == '1':
                    if not checkEmpty(data['借用人']):
                        flash('失败:在库时借用人必须为空,借用人=%s' % data['借用人'], 'err')
                        return redirect(url_for('main.show', name=depot.name))
                    if not checkEmpty(data['借用邮箱']):
                        flash('失败:在库时借用邮箱必须为空,借用邮箱=%s' % data['借用邮箱'], 'err')
                        return redirect(url_for('main.show', name=depot.name))
                    if not checkEmpty(data['借用数量']):
                        flash('失败:在库时借用数量必须为空,借用数量=%s' % data['借用数量'], 'err')
                        return redirect(url_for('main.show', name=depot.name))
                if status_dict[data['状态']] == '2':
                    if checkEmpty(data['借用人']):
                        flash('失败:借用人不能为空,借用人=%s' % data['借用人'], 'err')
                        return redirect(url_for('main.show', name=depot.name))
                    if checkEmpty(
                            data['借用邮箱']) or not checkEmail(data['借用邮箱']):
                        flash('失败:借用邮箱不能为空,且格式符合邮箱要求,借用邮箱=%s' % data['借用邮箱'],
                              'err')
                        return redirect(url_for('main.show', name=depot.name))
                    if checkEmpty(data['借用数量']) or not checkInt(data['借用数量']):
                        flash('失败:借用数量不能为空,且只能输入整数,借用数量=%s' % data['借用数量'],
                              'err')
                        return redirect(url_for('main.show', name=depot.name))
                    if checkEmpty(data['借用时间']) or not checkDate(data['借用时间']):
                        flash('失败:借用时间格式为年-月-日或年/月/日,借用数量=%s' % data['借用数量'],
                              'err')
                        return redirect(url_for('main.show', name=depot.name))
                    userinfo = {
                        'username': data['借用人'],
                        'usermail': data['借用邮箱'],
                        'lend_time': data['借用时间'],
                        'lend_numbers': data['借用数量']
                    }
                    kwargs.update(userinfo)
                cmp = T3(**kwargs)
                if T3.query.filter_by(assetnumber=data['资产编号']).count() > 0:
                    flash('失败:编号为%s的资产已存在' % data['资产编号'], 'err')
                    return redirect(url_for('main.show', name=depot.name))
                db.session.add(cmp)
            db.session.commit()
            flash('上传成功', 'success')
            return redirect(url_for('main.show', name=depot.name))
コード例 #14
0
def add_post():
    res = get_profile(session['username'])
    if not res:
        return render_template(
            'access_denied.html',
            error_msg="Error Occurred while fetching Profile Details",
            title="Error")
    if request.method == 'POST':
        # check if the post request has the file part
        post_headline = request.form.get('headline')
        multimedia = ''
        folder_name = ''
        posts = ''

        if 'image' in request.files and request.files['image'].filename != '':
            multimedia = 'image'
            folder_name = 'images'

        elif 'audio' in request.files and request.files['audio'].filename != '':
            multimedia = 'audio'
            folder_name = 'audios'

        elif 'video' in request.files and request.files['video'].filename != '':
            multimedia = 'video'
            folder_name = 'videos'
        elif 'document' in request.files and request.files[
                'document'].filename != '':
            multimedia = 'document'
            folder_name = 'documents'
        else:
            flash('No file selected for uploading')
            return redirect(request.url)

        file = request.files[multimedia]
        extension = file.filename.split('.')[-1]

        if file and allowed_file(extension):
            filename = secure_filename(file.filename)
            file.save(
                os.path.join(BLOB, session['username'], 'posts', folder_name,
                             filename))

            post_info = {
                "post_type":
                multimedia,
                "post_name":
                filename,
                "post_headline":
                post_headline,
                "base_price":
                request.form.get('base_price'),
                "bid_price": [],
                "bidding_person": [],
                "first_bidding_time":
                "N/A",
                "bidding_status":
                "open",
                "date_time_added":
                datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                "transaction_hash":
                "N/A"
            }

            str = session['username'] + "Patrons Pool Portal" + post_headline
            vpn = hashlib.sha256(str.encode())

            patent_info = {
                "vpn": vpn.hexdigest(),
                "headline": post_headline,
                "product_owners": []
            }

            patent_info['product_owners'].append({
                'type':
                'user',
                'username':
                session['username']
            })

            store_posts(post_info)
            store_patent(patent_info)
            posts = get_posts(session['username'])
            # searches for dockerfile in the extracted folder
            # call this function after the user presses on the submit button or so

            # The below mentioned is the mailing functionality, Creates a separate thread and triggers the emails to all the sponsors
            thread = Thread(target=mail_sponsers_when_a_post_is_added,
                            args=[app, session['username']])
            thread.start()

        else:
            return render_template(
                "home.html",
                search=False,
                posts=posts,
                profile=res,
                msg='Allowed file types are mp4, mp3, png, jpg, jpeg, gif',
                title="Home")
    return render_template("home.html",
                           search=False,
                           posts=posts,
                           profile=res,
                           msg='Added Successfully! :-D',
                           title="Home")
コード例 #15
0
ファイル: tests.py プロジェクト: dianvaltodorov/happy-commas
 def test_allowed_filenames(self):
     self.assertTrue(allowed_file("data.csv"))
     self.assertFalse(allowed_file("data"))
     self.assertFalse(allowed_file("data.png"))
     self.assertFalse(allowed_file("data.tar"))
     self.assertFalse(allowed_file("data.png.zip.tar"))
コード例 #16
0
ファイル: accessories.py プロジェクト: highoncarbs/noice
def add_accessories():
    if request.method == 'POST':
        payload = json.loads(request.form['data'])
        file = request.files

        if payload:
            try:
                uom = Uom.query.filter_by(id = int(payload['uom'])).first()
                new_data = Accessories(
                    payload['name'].lower().strip(), payload['desc'].lower(), payload['uom'])
                new_data.uom.append(uom)
                if len(file) != 0:
                    file = request.files['image']
                    try:

                        if file and allowed_file(file.filename):
                            filename = secure_filename(file.filename)
                            foldertemp = os.path.join(
                                UPLOAD_FOLDER, 'accessories')

                            if os.path.exists(foldertemp):
                                filetemp = os.path.join(
                                    foldertemp, filename)
                                file.save(filetemp)
                                setattr(new_data, 'image', filetemp)
                            else:

                                os.makedirs(foldertemp)

                                filetemp = os.path.join(
                                    foldertemp, filename)
                                file.save(filetemp)
                                setattr(new_data, 'image', filetemp)
                        else:
                            return jsonify({'message': 'Image file not supported.'})

                    except KeyError as e:
                        print(str(e))
                        pass

                    except Exception as e:
                        print(str(e))

                db.session.add(new_data)
                db.session.commit()
                return jsonify({'success': 'Data Added'})

            except sqlalchemy.exc.IntegrityError as e:
                print('Here' + str(e))
                db.session.rollback()
                db.session.close()
                return jsonify({'message': 'Duplicate entry for values.'})

            except Exception as e:
                print('Here' + str(e))
                db.session.rollback()
                db.session.close()
                return jsonify({'message': 'Something unexpected happened. Check logs', 'log': str(e)})
        else:
            return jsonify({'message': 'Empty Data.'})

    else:
        return jsonify({'message': 'Invalid HTTP method . Use POST instead.'})
コード例 #17
0
def upload():
    # print("request.files=",request.files)
    status_dict = {"在库": "1", "借出": "2"}
    if request.method == 'POST' and 'file' in request.files:
        f = request.files.get('file')
        # print("f=",f)
        filename = rename_file(f.filename)
        # print("filename=",filename)
        if allowed_file(f.filename):
            # print("*******start upload*********")
            if not os.path.exists(current_app.config['UPLOAD_PATH']):
                os.mkdir(current_app.config['UPLOAD_PATH'])
            path = os.path.join(current_app.config['UPLOAD_PATH'], filename)
            f.save(path)
        else:
            # print("*******error *********")
            flash('失败:上传文件格式错误,请上传文件后缀为.xls和.xlsx的文件', 'err')
            return redirect(url_for('book.index'))
        datas = read_excel(path)
        print('datas=', datas)
        # print("*******datas=",datas)
        #判断表格格式是否正确
        head = [
            '图书编号', '书名', '数量', '价格', '储位', '状态', '借用人', '借用邮箱', '借用时间',
            '预计归还时间'
        ]
        if not checkHead(head, datas[0]):
            flash("失败:上传文件表头信息错误,正确的表头信息为%s" % datas[0], 'err')
            return redirect(url_for('book.index'))
        #检查内容是否符合格式
        datas.remove(datas[0])
        for data in datas:
            if checkEmpty(data['图书编号']) or not checkType(
                    data['图书编号']) or not checkLength(data['图书编号'], 1, 255):
                flash(
                    "失败:图书编号不能为空,且只能输入数字、字母和下划线,范围:1-255,图书编号=%s" %
                    data['图书编号'], 'err')
                return redirect(url_for('book.index'))
            if checkEmpty(data['书名']) or not checkLength(data['书名'], 1, 255):
                flash("失败:书名不能为空,范围:1-255,书名=%s" % data['书名'], 'err')
                return redirect(url_for('book.index'))
            if checkEmpty(data['价格']) or not checkNumber(data['价格']):
                flash("失败:价格不能为空,且只能输入整数或小数,价格=%s" % data['价格'], 'err')
                return redirect(url_for('book.index'))
            if checkEmpty(data['储位']) or not checkType2(
                    data['储位']) or not checkLength(data['储位'], 1, 255):
                flash(
                    "失败:储位不能为空,且只能输入数字、字母、中文和下划线,范围:1-255,储位=%s" % data['储位'],
                    'err')
                return redirect(url_for('book.index'))
            kwargs = {
                'booknumber': data['图书编号'],
                'bookname': data['书名'],
                'numbers': data['数量'],
                'prices': data['价格'],
                'position': data['储位'],
                'status': status_dict[data['状态']]
            }
            # kwargs = {'bookname':data['书名'], 'numbers':data['数量'],'prices':data['价格'],'position':data['储位'],'status':status_dict[data['状态']]}
            if status_dict[data['状态']] == '1':
                if not checkEmpty(data['借用人']):
                    flash('失败:在库时借用人必须为空,借用人=%s' % data['借用人'], 'err')
                    return redirect(url_for('book.index'))
                if not checkEmpty(data['借用邮箱']):
                    flash('失败:在库时借用邮箱必须为空,借用邮箱=%s' % data['借用邮箱'], 'err')
                    return redirect(url_for('book.index'))
            elif status_dict[data['状态']] == '2':
                if checkEmpty(data['借用人']):
                    flash('失败:借用人不能为空,借用人=%s' % data['借用人'], 'err')
                    return redirect(url_for('book.index'))
                if checkEmpty(data['借用时间']) or not checkDate(data['借用时间']):
                    flash("失败:借用时间格式为年-月-日或年/月/日,借用时间=%s" % data['借用时间'],
                          'err')
                    return redirect(url_for('book.index'))
                if checkEmpty(data['预计归还时间']) or not checkDate(data['预计归还时间']):
                    flash("失败:预计归还时间格式为年-月-日或年/月/日,预计归还时间=%s" % data['预计归还时间'],
                          'err')
                    return redirect(url_for('book.index'))
                if checkCompareDate(data['借用时间'], data['预计归还时间']):
                    flash(
                        '失败:预计归还时间不能小于借用时间,借用时间=%s,预计归还时间=%s' %
                        (data['借用时间'], data['预计归还时间']), 'err')
                    return redirect(url_for('book.index'))
                userinfo = {
                    'username': data['借用人'],
                    'usermail': data['借用邮箱'],
                    'lendtime': data['借用时间'],
                    'backtime': data['预计归还时间']
                }
                kwargs.update(userinfo)
            if Book.query.filter_by(booknumber=data['图书编号']).count() > 0:
                flash('失败:编号为%s的图书%s已存在' % (data['图书编号'], data['书名']), 'err')
                return redirect(url_for('book.index'))
            cmp = Book(**kwargs)
            db.session.add(cmp)
        db.session.commit()
        flash('上传成功', 'success')
        return redirect(url_for('book.index'))
コード例 #18
0
ファイル: finished_item.py プロジェクト: highoncarbs/noice
def edit_finished_goods():
    if request.method == 'POST':
        payload = json.loads(request.form['data'])
        file = request.files
        print(payload)
        if payload:
            try:
                new_data = FinishedGoods.query.filter_by(
                    id=payload['id']).first()
                temp_image = new_data.image
                new_data.alt_name = payload['alt_name']
                product_category = ProductCategory.query.filter_by(
                    id=int(payload['product_category'])).first()
                fabric_combination = FabricCombination.query.filter_by(
                    id=int(payload['fabric_combination'])).first()
                print_technique = PrintTechnique.query.filter_by(
                    id=int(payload['print_technique'])).first()
                design_number = DesignNumber.query.filter_by(
                    id=int(payload['design_number'])).first()
                uom = Uom.query.filter_by(id=int(payload['uom'])).first()
                size = SizeMaster.query.filter_by(
                    id=int(payload['size'])).first()

                new_data.product_category_id = product_category.id
                new_data.fabric_combination_id = fabric_combination.id
                new_data.print_technique_id = print_technique.id
                new_data.design_number_id = design_number.id
                new_data.uom_id = uom.id
                new_data.size_id = size.id

                new_data.product_category = []
                new_data.print_technique = []
                new_data.fabric_combination = []
                new_data.design_number = []
                new_data.uom = []
                new_data.size = []

                new_data.product_category.append(product_category)
                new_data.fabric_combination.append(fabric_combination)
                new_data.print_technique.append(print_technique)
                new_data.design_number.append(design_number)
                new_data.uom.append(uom)
                new_data.size.append(size)

                if len(file) != 0:
                    file = request.files['image']
                    try:

                        if file and allowed_file(file.filename):
                            filename = secure_filename(file.filename)
                            foldertemp = os.path.join(UPLOAD_FOLDER,
                                                      'finished_goods')

                            if os.path.exists(foldertemp):
                                filetemp = os.path.join(foldertemp, filename)
                                print(filetemp)
                                file.save(filetemp)

                                new_data.image = filetemp
                            else:
                                os.makedirs(foldertemp)

                                filetemp = os.path.join(foldertemp, filename)
                                file.save(filetemp)
                                new_data.image = filetemp

                        else:
                            return jsonify(
                                {'message': 'Image file not supported.'})

                    except KeyError as e:
                        print(str(e))

                        pass

                    except Exception as e:
                        print(str(e))
                db.session.commit()
                return jsonify({'success': 'Data Updated'})

            except Exception as e:
                print(str(e))

                db.session.rollback()
                db.session.close()
                return jsonify({
                    'message': 'Something unexpected happened. Check logs',
                    'log': str(e)
                })
        else:
            return jsonify({'message': 'Empty Data.'})

    else:
        return jsonify({'message': 'Invalid HTTP method . Use POST instead.'})
コード例 #19
0
ファイル: finished_item.py プロジェクト: highoncarbs/noice
def add_finished_goods():
    if request.method == 'POST':
        print(request.form)
        payload = json.loads(request.form['data'])
        print(payload)
        file = request.files
        print(file)
        if payload:
            try:
                product_category = ProductCategory.query.filter_by(
                    id=int(payload['product_category'])).first()
                fabric_combination = FabricCombination.query.filter_by(
                    id=int(payload['fabric_combination'])).first()
                print_technique = PrintTechnique.query.filter_by(
                    id=int(payload['print_technique'])).first()
                design_number = DesignNumber.query.filter_by(
                    id=int(payload['design_number'])).first()
                uom = Uom.query.filter_by(id=int(payload['uom'])).first()
                size = SizeMaster.query.filter_by(
                    id=int(payload['size'])).first()

                new_data = FinishedGoods(payload['alt_name'],
                                         int(payload['product_category']),
                                         int(payload['fabric_combination']),
                                         int(payload['print_technique']),
                                         int(payload['design_number']),
                                         int(payload['uom']),
                                         int(payload['size']))
                new_data.product_category.append(product_category)
                new_data.fabric_combination.append(fabric_combination)
                new_data.print_technique.append(print_technique)
                new_data.design_number.append(design_number)
                new_data.uom.append(uom)
                new_data.size.append(size)

                if len(file) != 0:
                    file = request.files['image']
                    try:

                        if file and allowed_file(file.filename):
                            filename = secure_filename(file.filename)
                            foldertemp = os.path.join(UPLOAD_FOLDER,
                                                      'finished_goods')

                            if os.path.exists(foldertemp):
                                filetemp = os.path.join(foldertemp, filename)
                                file.save(filetemp)
                                setattr(new_data, 'image', filetemp)
                            else:

                                os.makedirs(foldertemp)

                                filetemp = os.path.join(foldertemp, filename)
                                file.save(filetemp)
                                setattr(new_data, 'image', filetemp)
                        else:
                            return jsonify(
                                {'message': 'Image file not supported.'})

                    except KeyError as e:
                        print(str(e))
                        pass

                    except Exception as e:
                        print(str(e))

                db.session.add(new_data)
                db.session.commit()
                return jsonify({'success': 'Data Added'})

            except sqlalchemy.exc.IntegrityError as e:
                print('Here' + str(e))
                db.session.rollback()
                db.session.close()
                return jsonify({'message': 'Duplicate entry for values.'})

            except Exception as e:
                print('Here' + str(e))
                db.session.rollback()
                db.session.close()
                return jsonify({
                    'message': 'Something unexpected happened. Check logs',
                    'log': str(e)
                })
        else:
            return jsonify({'message': 'Empty Data.'})

    else:
        return jsonify({'message': 'Invalid HTTP method . Use POST instead.'})
コード例 #20
0
def upload_image():
    """
    POST params:
        num_styles:
        scale:
        file:

    :return:
    """

    if request.method == "POST":
        if 'file' not in request.files:
            current_app.logger.debug('Error in Upload - No file part')
            return redirect(request.url)

        file = request.files['file']

        if file.filename == '':
            current_app.logger.debug('Error in Upload - No selected file')
            return redirect(request.url)

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            upload_path = os.path.join(current_app.config["UPLOAD_FOLDER"],
                                       filename)
            file.save(upload_path)

            # trigger neural net
            num_styles = request.form.get("num_styles", default=1, type=int)
            scale = request.form.get("scale", default=1.0, type=float)
            aligned = True if request.form.get(
                "aligned", default="false", type=str) == "true" else False

            from app import warpgan

            try:
                start = time.time()
                images = warpgan.trigger_nn(
                    upload_path, current_app.config["RESULTS_FOLDER"],
                    num_styles, scale, aligned)
                total = time.time() - start

            except Exception as e:
                current_app.logger.error(e.with_traceback(e.__traceback__))
                return jsonify({"error":
                                e.args}), 415  # Unsupported Media Type

            image_urls = [
                url_for("static", filename=f"results/{image}")
                for image in images
            ]

            os.remove(upload_path)

            return {
                "num_styles": num_styles,
                "time_taken": total,
                "image": image_urls
            }

        return {"msg": "error"}
コード例 #21
0
def upload():
    try:
        content_type = request.content_type
        if content_type is None:
            return server_response(error=CONTENT_TYPE_INVALID), 400
        if CONTENT_TYPE_MULTIPART not in content_type:
            return server_response(error=CONTENT_TYPE_INVALID), 400
        if request.method == METHOD_POST:
            if FILE not in request.files:
                return server_response(error=KEY_MISSING.format(FILE)), 400
            user_id = str(request.environ.get(USER_ID))
            if user_id is None:
                return server_response(error=KEY_MISSING.format(USER_ID)), 400

            file = request.files[FILE]
            if file.filename == '':
                return server_response(error=FILE_NAME_EMPTY), 400
            if not allowed_file(file.filename):
                return server_response(error=FILE_NOT_ALLOWED), 400

            if not userDao.is_user_exists(user_id):
                return server_response(error=USER_NOT_EXISTS), 400

            # to_ext = ".pdf"
            # if TO_EXT in request.form:
            #     to_ext = request.form.get(TO_EXT)

            full_filename = secure_filename(file.filename)
            # upload folder path
            file_upload_dir = os.path.join(app.config[UPLOAD_FOLDER], user_id)
            # convert folder path
            file_convert_dir = os.path.join(app.config[CONVERTED_FOLDER],
                                            user_id)

            # create upload dir for user
            if not os.path.exists(file_upload_dir):
                os.makedirs(file_upload_dir)

            # create convert dir for user
            if not os.path.exists(file_convert_dir):
                os.makedirs(file_convert_dir)

            # name and extension
            filename_only, file_ext = os.path.splitext(full_filename)
            # timestamp
            timestamp = get_timestamp()
            # create uploaded file name
            temp_upload_file_name = '{}{}'.format(timestamp, file_ext)
            # create upload path
            file_upload_path = os.path.join(file_upload_dir,
                                            temp_upload_file_name)
            # save uploaded file
            file.save(file_upload_path)
            file_size = os.stat(file_upload_path).st_size

            # create convert filename
            temp_convert_file_name = '{}.pdf'.format(timestamp)
            # create convert path
            file_convert_path = os.path.join(file_convert_dir,
                                             temp_convert_file_name)

            size_unit = SizeUnits.BYTES.name

            success, file_data = conversionDao.create(
                user_id, full_filename, filename_only, file_ext, '.pdf',
                file_size, file_upload_path, file_convert_path, size_unit)
            if success:
                # Add task for file conversion
                job: Job = app.queue.enqueue(convert_file, file_data)
                # update task id
                conversionDao.update_task_id(file_data.id, job.id)
                return server_response(data=file_data.toJSON(),
                                       message=FILE_UPLOADED_SUCCESS), 200
            else:
                return server_response(error=SOMETHING_WENT_WRONG), 500
        else:
            return server_response(error=SOMETHING_WENT_WRONG), 500
    except RequestEntityTooLarge as e:
        print(e)
        return server_response(error=FILE_SIZE_TOO_LARGE), 400
コード例 #22
0
ファイル: accessories.py プロジェクト: highoncarbs/noice
def edit_accessories():
    if request.method == 'POST':
        payload = json.loads(request.form['data'])
        file = request.files
        print(payload)
        if payload:
            try:
                new_data = Accessories.query.filter_by(
                    id=payload['id']).first()

                uom = Uom.query.filter_by(id=int(payload['uom'])).first()

                temp_image = new_data.image
                new_data.name = payload['name'].lower().strip()
                new_data.desc = payload['desc'].lower().lower()
                new_data.uom_id = uom.id
                new_data.uom = []
                new_data.uom.append(uom)

                if len(file) != 0:
                    file = request.files['image']
                    try:

                        if file and allowed_file(file.filename):
                            filename = secure_filename(file.filename)
                            foldertemp = os.path.join(
                                UPLOAD_FOLDER, 'accessories')

                            if os.path.exists(foldertemp):
                                filetemp = os.path.join(
                                    foldertemp, filename)
                                file.save(filetemp)

                                new_data.image = filetemp
                            else:
                                os.makedirs(foldertemp)

                                filetemp = os.path.join(
                                    foldertemp, filename)
                                file.save(filetemp)
                                new_data.image = filetemp

                        else:
                            return jsonify({'message': 'Image file not supported.'})

                    except KeyError as e:
                        print(str(e))

                        pass

                    except Exception as e:
                        print(str(e))
                db.session.commit()
                return jsonify({'success': 'Data Updated'})

            except Exception as e:
                print(str(e))

                db.session.rollback()
                db.session.close()
                return jsonify({'message': 'Something unexpected happened. Check logs', 'log': str(e)})
        else:
            return jsonify({'message': 'Empty Data.'})

    else:
        return jsonify({'message': 'Invalid HTTP method . Use POST instead.'})
コード例 #23
0
def edit_raw_goods():
    if request.method == 'POST':
        payload = json.loads(request.form['data'])
        file = request.files
        print(payload)
        if payload:
            try:
                new_data = RawGoods.query.filter_by(
                    id=payload['id']).first()
                temp_image = new_data.image
                new_data.alt_name = payload['alt_name']
                yarn = Yarn.query.filter_by(
                    id=int(payload['yarn'])).first()
                fabric_process = FabricProcess.query.filter_by(
                    id=int(payload['fabric_process'])).first()
                fabric_width = FabricWidth.query.filter_by(
                    id=int(payload['fabric_width'])).first()
                fabric_dye = FabricDye.query.filter_by(
                    id=int(payload['fabric_dye'])).first()
                raw_material_category = RawMaterialCategory.query.filter_by(
                    id=int(payload['raw_material_category'])).first()
                fabric_construction = FabricConstruction.query.filter_by(
                    id=int(payload['fabric_construction'])).first()
                uom = Uom.query.filter_by(
                    id=int(payload['uom'])).first()

                new_data.yarn_id = yarn.id
                new_data.fabric_process_id =fabric_process.id
                new_data.fabric_width_id = fabric_width.id
                new_data.fabric_dye_id = fabric_dye.id
                new_data.raw_material_category_id = raw_material_category.id
                new_data.fabric_construction_id = fabric_construction.id
                new_data.uom_id = uom.id

                new_data.yarn = []
                new_data.fabric_process = []
                new_data.fabric_width = []
                new_data.fabric_dye = []
                new_data.raw_material_category = []
                new_data.fabric_construction = []
                new_data.uom = []

                new_data.yarn.append(yarn)
                new_data.fabric_process.append(fabric_process)
                new_data.fabric_width.append(fabric_width)
                new_data.fabric_dye.append(fabric_dye)
                new_data.raw_material_category.append(raw_material_category)
                new_data.fabric_construction.append(fabric_construction)
                new_data.uom.append(uom)

                if len(file) != 0:
                    file = request.files['image']
                    try:

                        if file and allowed_file(file.filename):
                            filename = secure_filename(file.filename)
                            foldertemp = os.path.join(
                                UPLOAD_FOLDER, 'raw_goods')

                            if os.path.exists(foldertemp):
                                filetemp = os.path.join(
                                    foldertemp, filename)
                                print(filetemp)
                                file.save(filetemp)

                                new_data.image = filetemp
                            else:
                                os.makedirs(foldertemp)

                                filetemp = os.path.join(
                                    foldertemp, filename)
                                file.save(filetemp)
                                new_data.image = filetemp

                        else:
                            return jsonify({'message': 'Image file not supported.'})

                    except KeyError as e:
                        print(str(e))

                        pass

                    except Exception as e:
                        print(str(e))
                db.session.commit()
                return jsonify({'success': 'Data Updated'})

            except Exception as e:
                print(str(e))

                db.session.rollback()
                db.session.close()
                return jsonify({'message': 'Something unexpected happened. Check logs', 'log': str(e)})
        else:
            return jsonify({'message': 'Empty Data.'})

    else:
        return jsonify({'message': 'Invalid HTTP method . Use POST instead.'})
コード例 #24
0
ファイル: routes.py プロジェクト: highoncarbs/noice
def update_transaction(id):
    if request.method == 'POST':
        print(request.form)
        payload = json.loads(request.form['data'])
        print(payload)
        file = request.files

        if payload:
            try:
                trans = Production.query.filter_by(id=int(id)).first()

                if len(file) != 0:
                    file = request.files['image']
                    try:
                        if file and allowed_file(file.filename):
                            filename = secure_filename(file.filename)
                            foldertemp = os.path.join(UPLOAD_FOLDER,
                                                      'transaction_report')

                            if os.path.exists(foldertemp):
                                filetemp = os.path.join(foldertemp, filename)
                                file.save(filetemp)
                                setattr(trans, 'image', filetemp)
                            else:

                                os.makedirs(foldertemp)

                                filetemp = os.path.join(foldertemp, filename)
                                file.save(filetemp)
                                setattr(trans, 'image', filetemp)
                        else:
                            return jsonify(
                                {'message': 'Image file not supported.'})

                    except KeyError as e:
                        print(str(e))
                        pass

                    except Exception as e:
                        print(str(e))

                temp_date = payload['date'].split('-')
                start_date = datetime(int(temp_date[0]), int(temp_date[1]),
                                      int(temp_date[2]))
                trans.flag = payload['status']
                trans.finished_goods_code = payload['finished_goods_code']
                trans.quantity = payload['quantity']
                trans.report = payload['report']
                trans.date = start_date

                db.session.commit()

                return jsonify({'success': 'Data Added'})

            except sqlalchemy.exc.IntegrityError as e:
                print('Here' + str(e))
                db.session.rollback()
                db.session.close()
                return jsonify({'message': 'Duplicate entry for values.'})

            except Exception as e:
                print('Here' + str(e))
                db.session.rollback()
                db.session.close()
                return jsonify({
                    'message': 'Something unexpected happened. Check logs',
                    'log': str(e)
                })
        else:
            return jsonify({'message': 'Empty Data.'})

    else:
        return jsonify({'message': 'Invalid HTTP method . Use POST instead.'})
コード例 #25
0
def add_raw_goods():
    if request.method == 'POST':
        print(request.form)
        payload = json.loads(request.form['data'])
        print(payload)
        file = request.files

        if payload:
            try:
                yarn = Yarn.query.filter_by(
                    id=int(payload['yarn'])).first()
                fabric_process = FabricProcess.query.filter_by(
                    id=int(payload['fabric_process'])).first()
                fabric_width = FabricWidth.query.filter_by(
                    id=int(payload['fabric_width'])).first()
                fabric_dye = FabricDye.query.filter_by(
                    id=int(payload['fabric_dye'])).first()
                raw_material_category = RawMaterialCategory.query.filter_by(
                    id=int(payload['raw_material_category'])).first()
                fabric_construction = FabricConstruction.query.filter_by(
                    id=int(payload['fabric_construction'])).first()
                uom = Uom.query.filter_by(
                    id=int(payload['uom'])).first()
                new_data = RawGoods(
                    payload['alt_name'], int(payload['yarn']), int(payload['fabric_process']), int(payload['fabric_width']), int(payload['fabric_dye']), int(payload['raw_material_category']), int(payload['fabric_construction']) , int(payload['uom']))
                
                new_data.yarn.append(yarn)
                new_data.fabric_process.append(fabric_process)
                new_data.fabric_width.append(fabric_width)
                new_data.fabric_dye.append(fabric_dye)
                new_data.raw_material_category.append(raw_material_category)
                new_data.fabric_construction.append(fabric_construction)
                new_data.uom.append(uom)

                if len(file) != 0:
                    file = request.files['image']
                    try:

                        if file and allowed_file(file.filename):
                            filename = secure_filename(file.filename)
                            foldertemp = os.path.join(
                                UPLOAD_FOLDER, 'raw_goods')

                            if os.path.exists(foldertemp):
                                filetemp = os.path.join(
                                    foldertemp, filename)
                                file.save(filetemp)
                                setattr(new_data, 'image', filetemp)
                            else:

                                os.makedirs(foldertemp)

                                filetemp = os.path.join(
                                    foldertemp, filename)
                                file.save(filetemp)
                                setattr(new_data, 'image', filetemp)
                        else:
                            return jsonify({'message': 'Image file not supported.'})

                    except KeyError as e:
                        print(str(e))
                        pass

                    except Exception as e:
                        print(str(e))

                db.session.add(new_data)
                db.session.commit()
                return jsonify({'success': 'Data Added'})

            except sqlalchemy.exc.IntegrityError as e:
                print('Here' + str(e))
                db.session.rollback()
                db.session.close()
                return jsonify({'message': 'Duplicate entry for values.'})

            except Exception as e:
                print('Here' + str(e))
                db.session.rollback()
                db.session.close()
                return jsonify({'message': 'Something unexpected happened. Check logs', 'log': str(e)})
        else:
            return jsonify({'message': 'Empty Data.'})

    else:
        return jsonify({'message': 'Invalid HTTP method . Use POST instead.'})