예제 #1
0
def new_furniture():
    json = request.json
    preview_id = json['preview']
    graphic_model_id = json['model']
    preview_file = FileModel(id=preview_id).objects.first()
    graphic_file = FileModel(id=graphic_model_id).objects.first()
    token = json['token']
    category = json['category']
    cat = Category.objects(name=category).first()
    if not cat:
        cat = Category(name=category).save()
    name = decode_token(token)
    if name is TOKEN_EXPIRED and name is TOKEN_INVALID:
        return '', 400
    company = Company.objects(name=name).first()
    company.categories.append(cat)  # FIXME all mongoengine queries
    company.save()
    if not company:
        return '', 400
    furn = Furniture(
        seller=company,
        name=json['name'],
        category=cat,
        price=json['price'],
        graphic_model=graphic_file,
        preview_file=preview_file,
    ).save()
    company.furniture.append(furn)
    company.save()
    cat.companies.append(company)
    cat.furniture.append(furn)
    cat.save()
    return jsonify({'id': str(furn.id)}), 201
예제 #2
0
def files():
    if not request.files['file']:
        return '', 400
    file = FileModel()
    file.file.put(request.files['file'],
                  content_type=request.files['file'].content_type,
                  filename=request.files['file'].filename)
    file.save()
    return jsonify({'id': str(file.id)})
예제 #3
0
 def setUp(self):
     self.obj = FileModel()
     if not os.path.isdir(temp_storage.location):
         os.makedirs(temp_storage.location)
     if os.path.isdir(UPLOAD_TO):
         os.chmod(UPLOAD_TO, 0700)
         shutil.rmtree(UPLOAD_TO)
예제 #4
0
def file_upload_view_verify(request):
    """
    Use the sha digest hash to verify the uploaded contents.
    """
    form_data = request.POST.copy()
    form_data.update(request.FILES)

    # Check to see if unicode names worked out.
    if not request.FILES['file_unicode'].name.endswith(
            u'test_\u4e2d\u6587_Orl\xe9ans.jpg'):
        return HttpResponseServerError()

    for key, value in form_data.items():
        if key.endswith('_hash'):
            continue
        if key + '_hash' not in form_data:
            continue
        submitted_hash = form_data[key + '_hash']
        if isinstance(value, UploadedFile):
            new_hash = sha_constructor(value.read()).hexdigest()
        else:
            new_hash = sha_constructor(value).hexdigest()
        if new_hash != submitted_hash:
            return HttpResponseServerError()

    # Adding large file to the database should succeed
    largefile = request.FILES['file_field2']
    obj = FileModel()
    obj.testfile.save(largefile.name, largefile)

    return HttpResponse('')
예제 #5
0
def file_upload_view_verify(request):
    """
    Use the sha digest hash to verify the uploaded contents.
    """
    form_data = request.POST.copy()
    form_data.update(request.FILES)

    for key, value in form_data.items():
        if key.endswith('_hash'):
            continue
        if key + '_hash' not in form_data:
            continue
        submitted_hash = form_data[key + '_hash']
        if isinstance(value, UploadedFile):
            new_hash = hashlib.sha1(value.read()).hexdigest()
        else:
            new_hash = hashlib.sha1(value).hexdigest()
        if new_hash != submitted_hash:
            return HttpResponseServerError()

    # Adding large file to the database should succeed
    largefile = request.FILES['file_field2']
    obj = FileModel()
    obj.testfile.save(largefile.name, largefile)

    return HttpResponse('')
예제 #6
0
def file_upload_filename_case_view(request):
    """
    Check adding the file to the database will preserve the filename case.
    """
    file = request.FILES['file_field']
    obj = FileModel()
    obj.testfile.save(file.name, file)
    return HttpResponse('%d' % obj.pk)
예제 #7
0
def ocr(ocrFile):
    """
    机动车销售发票 OCR识别
    :return:
    """
    app_sys = get_app_sys(ocrFile.app_sys_code)
    Assert.is_true(is_not_empty(app_sys),
                   '无效的应用系统:{0}'.format(ocrFile.app_sys_code),
                   codes.unprocessable)
    # 通过外键添加
    ocrFile.app_sys_id = app_sys.id

    file_model = FileModel()
    file_model.dao_create()

    # 资料写入磁盘
    file_path = encodes.base64_to_file(ocrFile.file_data.file_base64,
                                       current_app.config.get('OCR_FILE_DIR'),
                                       file_model.id,
                                       ocrFile.file_data.file_format)

    # OCR识别
    token = SysData().dao_get_key(system.SysKey.HUAWEI_CLOUD_TOKEN.value).value
    mvsi_result = OCR(token=token)\
        .mvsi(image_bs64=img.ImgUtil.img_compress(path=file_path, threshold=5))
    Assert.is_true(
        is_empty(mvsi_result.error_code),
        'OCR FAILED: 【{0}】【{1}】'.format(mvsi_result.error_code,
                                        mvsi_result.error_msg))
    mvsi_result_json, errors = MvsiResultSchema(
        only=MvsiResultSchema().only_success()).dump(mvsi_result)
    Assert.is_true(is_empty(errors), errors)

    # 信息入库
    mvsi = Mvsi(**mvsi_result_json)
    mvsi.dao_add(ocrFile, file_model, file_path)

    # json 序列化
    mvsi_json, errors = MvsiSchema().dump(mvsi)
    Assert.is_true(is_empty(errors), errors)
    return render_info(MyResponse('OCR SUCCESS', results=mvsi_json))
예제 #8
0
파일: views.py 프로젝트: cyrilsx/smart_cms
def edit_file(request, id=None):
    data = {}
    file = FileModel()
    
    if request.method == "POST":
        form = FileForm(request.POST,instance=file) # A form bound to the POST data
        if form.is_valid():
            file.file_name = form.cleaned_data['file_name']
            file.caption = form.cleaned_data['caption']

            file.save()
            #return HttpResponseRedirect('/blog/view/%s' % article.id)
    elif request.method == "GET":
        if id != None:
            file = FileModel.objects.get(pk=id)
        form = FileForm(instance=file)
    else:
        raise Http404

    data['form'] = form
    return render_to_response(BLOG_TEMPLATE + 'edit.html', data, context_instance=RequestContext(request))
예제 #9
0
    async def post(self):
        """"POST method that reciev files in form
         data with uuid in as query parameter"""
        file1 = self.request.files['file'][0]
        file_name = file1.get('filename')  # not sure
        uuid = self.get_query_argument('uuid')
        required_data = [file1, uuid]
        for field in required_data:
            if not field:
                return self.finish_with_error(
                    code=400,
                    detail={'Error': 'No required'
                            'param: '
                            f'{field}'})

        try:
            file = str(file1.body, 'utf-8')
            file_data = file.split('\n')
            for x in file_data:
                if x == '':
                    file_data.remove(x)
            dict_list = get_data_list(file_data)
            logging.warning(f'Dict - data {dict_list} type -'
                            f' {type(dict_list)}')
        except Exception as e:
            logging.warning(f"Error format validation")
            return self.finish_with_error(code=400,
                                          detail={'Validation error': f'{e}'})

        key_list = [list(x.keys()) for x in dict_list]
        value_list = [list(x.values()) for x in dict_list]

        pure_key_list = []
        for x in key_list:
            pure = x[0]
            pure_key_list.append(pure)

        pure_value_list = []
        for x in value_list:
            pure = int(x[0])
            pure_value_list.append(pure)

        file_obj = FileModel(data_list=dict_list,
                             uuid=uuid,
                             name=file_name,
                             key_list=pure_key_list,
                             value_list=pure_value_list)
        logging.warning(f'{file_obj.key_list, file_obj.value_list}')
        file_list_holder.append(file_obj)
        logging.warning(f'{file_list_holder}')

        return self.finish()
예제 #10
0
def file_download(id, md5_id, as_attachment=None):
    """
    文件下载
    :param id:
    :param md5_id:
    :param as_attachment:
    :return:
    """
    as_attachment = True if is_empty(as_attachment) else False
    file = FileModel().dao_down_file(id, md5_id)  # type: FileModel
    return download_file(file.file_path,
                         '{0}.{1}'.format(file.file_name, file.file_format),
                         as_attachment=as_attachment)
예제 #11
0
class DirectoryCreationTests(unittest.TestCase):
    """
    Tests for error handling during directory creation
    via _save_FIELD_file (ticket #6450)
    """
    def setUp(self):
        self.obj = FileModel()
        if not os.path.isdir(UPLOAD_ROOT):
            os.makedirs(UPLOAD_ROOT)

    def tearDown(self):
        os.chmod(UPLOAD_ROOT, 0700)
        shutil.rmtree(UPLOAD_ROOT)

    def test_readonly_root(self):
        """Permission errors are not swallowed"""
        os.chmod(UPLOAD_ROOT, 0500)
        try:
            self.obj.save_testfile_file('foo.txt', SimpleUploadedFile('foo.txt', 'x'))
        except OSError, err:
            self.assertEquals(err.errno, errno.EACCES)
        except:
예제 #12
0
def dashboard_add_patient():
    if request.method == 'POST':
        name = request.form.get('name')
        email = request.form.get('email')
        age = request.form.get('age')
        national_id = request.form.get('national_id')
        medical_history = request.form.get('medical_history')
        phone_num = request.form.get('phone_num')
        Address = request.form.get('Address')
        gender = request.form.get('gender')
        enter = str(request.form.get('enter'))
        imagesList = request.files.getlist("inputFile")

        check = PatientModel.query.filter_by(national_id=national_id).first()

        if check:  # if a patient already exists by its id, we flash a msg that he is already in the database.
            flash('Patient with same ID already exists.')
            return redirect(url_for('auth.dashboard_control_form'))

        patient = PatientModel(name=name,
                               email=email,
                               age=age,
                               national_id=national_id,
                               medical_history=medical_history,
                               phone_num=phone_num,
                               Address=Address,
                               gender=gender,
                               enter=enter,
                               action="No Action added yet.")

        db.session.add(patient)
        db.session.commit()

        folder_path = os.path.join("static", "images", str(patient.id))
        os.mkdir(folder_path)

        for image in imagesList:
            newFile = FileModel(name=os.path.join(folder_path, image.filename),
                                patient_id=patient.id)
            image.save(os.path.join(folder_path, image.filename))
            db.session.add(newFile)

        db.session.commit()
        flash(f"{patient.name} has been successfully added to the system!")

        return render_template('dashboard-control.html')

    else:

        return render_template('dashboard-control.html')
예제 #13
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('file',
                            type=werkzeug.datastructures.FileStorage,
                            location='files',
                            required=True,
                            help='File cannot be blank!')
        args = parser.parse_args()

        img = Image.open(args['file'])

        file = FileModel(creation_date=datetime.now(utc), size=img.size)
        file_manager.insert_file(file)
        return file, status.HTTP_201_CREATED
예제 #14
0
def dashboard_edit_patient():
    if request.method == 'POST':  # check if there is post data
        national_id = request.form.get('national_id')
        new_email = request.form.get('new_email')
        new_phone_num = request.form.get('new_phone_num')
        new_medical_history = request.form.get('new_medical_history')
        new_Address = request.form.get('new_Address')
        imagesList = request.files.getlist("inputFile")

        patient = PatientModel.query.filter_by(national_id=national_id).first()

        if patient:
            patient.medical_history = new_medical_history
            patient.email = new_email
            patient.Address = new_Address
            patient.phone_num = new_phone_num
            folder_path = os.path.join("static", "images", str(patient.id))

            if not FileModel.query.filter_by(patient_id=patient.id).first():
                folder_path = os.path.join("static", "images", str(patient.id))
                os.mkdir(folder_path)

            for image in imagesList:
                newFile = FileModel(name=os.path.join(folder_path,
                                                      image.filename),
                                    patient_id=patient.id)
                image.save(os.path.join(folder_path, image.filename))
                db.session.add(newFile)

            db.session.commit()
            flash(f"{patient.name} has been successfully Updated!")
        else:
            flash(
                "There's no patient on the database with the national_id you entered. Please try again with correct inputs."
            )
        return redirect(url_for('auth.dashboard_control_form'))

    return render_template('dashboard-control.html')
예제 #15
0
    def _get(self, message):
        GEN_PORT = -1 # Unvalid
        while True:
            GEN_PORT = random.randint(6666,9999)
            if GEN_PORT not in self.port_list:
                self.port_list.append(GEN_PORT)
                break
            else:
                continue

        if not GEN_PORT:
            print "Port full"

        requested_file = FileModel.objects(name=message[1]).first()
        if requested_file:
            for cl in self.server.client_list:
                if str(cl.address) == requested_file.client.addr:
                    self.client.update('UDP_LISTEN:%s:%d:%s:%s' % (self.client.address[0], GEN_PORT, requested_file.name,requested_file.checksum))
                    cl.update('UDP_SEND:%s:%d:%s' % (
                        self.client.address[0], GEN_PORT, message[1])
                    )
        else:
            self.client.update(message='NOK:Errno(4)')
예제 #16
0
 def setUp(self):
     self.obj = FileModel()
     if not os.path.isdir(temp_storage.location):
         os.makedirs(temp_storage.location)
예제 #17
0
 def setUp(self):
     self.obj = FileModel()
     if not os.path.isdir(UPLOAD_ROOT):
         os.makedirs(UPLOAD_ROOT)
예제 #18
0
user2 = UserModel(name='B', email='*****@*****.**')
user3 = UserModel(name='C', email='*****@*****.**')
user4 = UserModel(name='D', email='*****@*****.**')
user5 = UserModel(name='E', email='*****@*****.**')
user6 = UserModel(name='F', email='*****@*****.**')
user7 = UserModel(name='G', email='*****@*****.**')
user8 = UserModel(name='H', email='*****@*****.**')
user9 = UserModel(name='I', email='*****@*****.**')
user10 = UserModel(name='J', email='*****@*****.**')
user11 = UserModel(name='K', email='*****@*****.**')
user12 = UserModel(name='L', email='*****@*****.**')
user13 = UserModel(name='M', email='*****@*****.**')
user14 = UserModel(name='N', email='*****@*****.**')
user15 = UserModel(name='O', email='*****@*****.**')

file1 = FileModel(name='File 1', typename='text')
file2 = FileModel(name='File 2', typename='mp3')
file3 = FileModel(name='File 3', typename='pdf')
file4 = FileModel(name='File 4', typename='text')
file5 = FileModel(name='File 5', typename='mp3')
file6 = FileModel(name='File 6', typename='text')
file7 = FileModel(name='File 7', typename='text')
file8 = FileModel(name='File 8', typename='mp3')
file9 = FileModel(name='File 9', typename='text')
file10 = FileModel(name='File 10', typename='mp3')
file11 = FileModel(name='File 11', typename='pdf')
file12 = FileModel(name='File 12', typename='mp3')
file13 = FileModel(name='File 13', typename='text')
file14 = FileModel(name='File 14', typename='text')
file15 = FileModel(name='File 15', typename='mp3')
file16 = FileModel(name='File 16', typename='text')