def save_image(file: FileStorage): thumbnail_size = 240, 240 directory = app.config["IMAGE_DIRECTORY"] # Compute hash file_hash = hashlib.md5(file.read()).hexdigest() file.seek(0) file_name = file_hash + ".jpg" file_path = os.path.join(directory, file_name) thumbnail_name = file_hash + "_thumb.jpg" thumbnail_path = os.path.join(directory, thumbnail_name) image = Image.open(file) size = image.size if not os.path.isfile(file_path): # save as jpg for size efficiency image.save(file_path) print("Saved image as", file_path) if not os.path.isfile(thumbnail_path): # create thumbnail image = Image.open(os.path.join(directory, file_name)) image.thumbnail(thumbnail_size, Image.ANTIALIAS) image.save(os.path.join(directory, thumbnail_name)) print("saved thumbnail as", thumbnail_path) store_image(file_hash, size)
def test_attachment_from_file_storage(): blob = randStream() filename = randUnicode() content_type = "y/x" metadata = AttachmentMetadata(filename, content_type) _file = FileStorage(stream=blob, filename=filename, content_type=content_type) input_file = copy.deepcopy(_file) attachment = Attachment.fromFileStorage(input_file, metadata) assert attachment.content.content == _file.read() assert attachment.metadata.filename == filename assert attachment.metadata.content_type == content_type assert attachment.metadata.content_disposition == AttachmentType.ATTACHMENT # test content_type correction blob = randStream() filename = randUnicode() content_type = "badcontenttype" metadata = AttachmentMetadata(filename, content_type) _file = FileStorage(stream=blob, filename=filename, content_type=content_type) input_file = copy.deepcopy(_file) attachment = Attachment.fromFileStorage(input_file, metadata) assert attachment.content.content == _file.read() assert attachment.metadata.filename == filename assert attachment.metadata.content_type == "application/octet-stream" assert attachment.metadata.content_disposition == AttachmentType.ATTACHMENT
class SaveAttachmentTest(MailgunTestBase): def setUp(self): super(SaveAttachmentTest, self).setUp() (filename, file_stream) = get_attachment() self.attachment = FileStorage(stream=file_stream, filename=filename) def tearDown(self): super(SaveAttachmentTest, self).tearDown() self.attachment.close() def test_fileallowed(self): self.assertTrue(self.mailgun._is_file_allowed('test.txt')) self.assertFalse(self.mailgun._is_file_allowed('bob')) def test_save_attachments(self): testdir = tempfile.mkdtemp() self.attachment.seek(0) filenames = save_attachments([self.attachment], testdir) filenames = [os.path.basename(filename) for filename in filenames] self.assertTrue(set(os.listdir(testdir)) == set(filenames)) self.assertEqual(len(os.listdir(testdir)), 1) shutil.rmtree(testdir) with self.assertRaises(OSError): os.listdir(testdir)
def download_header_image(self): req = requests.get(self.header_image, stream=True) storage = FileStorage(stream=iter_to_stream(req.iter_content(chunk_size=10))) key = str(b32encode(urandom(15)), "utf8") ext = mimetypes.guess_extension(req.headers["content-type"]) name = key + ext storage.save(os.path.join(app.config["UPLOAD_FOLDER"], name)) self.header_image = url_for('uploads', filename=name)
def save_image_file(image_file: FileStorage) -> str: """Saves the specified image to the filesystem.""" fd, filename = tempfile.mkstemp(dir=app.image_directory) try: app.logger.debug(f"Saving image file {image_file} as {filename}") with open(fd, 'wb') as f: image_file.save(f) validate_image_file(filename) except Exception as e: with contextlib.suppress(OSError): os.remove(filename) raise e return filename
def upload_file(): filename = request.args.get('file') # Get the name of the uploaded file filepath = os.path.join(app.config['DATA_FOLDER'], filename) with open(filepath, 'r') as fp: file = FileStorage(fp) # Check if the file is valid if file: # Make the filename safe, remove unsupported chars filename = secure_filename(file.filename) # Move the file form the temporal folder to # the upload folder we setup file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) # Redirect the user to the uploaded_file route, which # will basicaly show on the browser the uploaded file return redirect(url_for('uploaded_file', filename=filename))
def setUp(self): self.app.config['UPLOAD_FOLDER'] = tempfile.mkdtemp() self.upload_folder = pathlib.Path(self.app.config['UPLOAD_FOLDER']) path = pathlib.Path(BASEDIR) path = path / 'testdata' / 'images' / 'testimage1.jpg' imagefile = path imagefile = FileStorage( stream=open(str(path), 'br'), filename=str(path), headers=Headers([('Content-Type', 'image/jpeg')]), ) with patch( target='project.tasks.uploads.celery_make_thumbnail.delay', new=make_thumbnail, ): UploadedImage.bl.save_image( image=imagefile, img_category=UploadedImage.IMG_CATEGORY.other, title='testing image', description='testing image', ) imagefile.close()
def client_save(): imgstr = re.search(r'base64,(.*)', request.form['file']).group(1) ext = re.search(r'data:image/(\w+)', request.form['file']).group(1) decoded_data = imgstr.decode('base64') file_data = cStringIO.StringIO(decoded_data) file = FileStorage(file_data, filename=generate_file_name(ext)) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) new_design = Design(filename, g.user.id) db.session.add(new_design) db.session.commit() elements = json.loads(request.form['parts']) for element in elements: new_element = Element(new_design.id, 2, element[1], element[0], element[2], element[3]) db.session.add(new_element) db.session.commit() return "success", 200
def test_ms_mzml_converter_composer(): params = {'mass': 230.079907196} with open(target_dir + source_dir + '/ms/svs813f1.mzML', 'rb') as f: file = FileStorage(f) file = FileContainer(file) mscv = MSConverter(file, params) mscp = MSComposer(mscv) lines = mscp.tf_jcamp().read()[:800] \ .decode('utf-8', errors='ignore').split('\n') assert '##$CSSCANAUTOTARGET=3' in lines assert '##$CSSCANEDITTARGET=3' in lines assert '##$CSSCANCOUNT=24' in lines assert '##$CSTHRESHOLD=0.05' in lines assert '51.012176513671875, 34359.0' in lines
def test_single_image(client): filename = 'lion.jpg' path = os.path.join(IMAGES_TESTING_DIR, filename) with open(path, "rb") as f: data = f.read() file_to_test = FileStorage( # simulating download process stream=io.BytesIO(data), filename= filename, # name with which the file will be saved at ./upload directory content_type="image/jpg", ) data = {'file[]': file_to_test} # prepared data to be sent response = client.post('/', data=data, content_type="multipart/form-data") assert response.status_code == 302 path_filename = os.path.join(DEPLOY_DIR, filename) assert os.path.exists( path_filename) # checking if the file was actually downloaded
def uploads_endpoint(request): """ Endpoint for file uploads """ username = request.matchdict["username"] requested_user = LocalUser.query.filter(LocalUser.username==username).first() if requested_user is None: return json_error("No such 'user' with id '{}'".format(username), 404) if request.method == "POST": # Ensure that the user is only able to upload to their own # upload endpoint. if requested_user.id != request.user.id: return json_error( "Not able to post to another users feed.", status=403 ) # Wrap the data in the werkzeug file wrapper if "Content-Type" not in request.headers: return json_error( "Must supply 'Content-Type' header to upload media." ) mimetype = request.headers["Content-Type"] if "X-File-Name" in request.headers: filename = request.headers["X-File-Name"] else: filenames = sorted(mimetypes.guess_all_extensions(mimetype)) if not filenames: return json_error('Unknown mimetype: {}'.format(mimetype), status=415) filename = 'unknown{}'.format(filenames[0]) file_data = FileStorage( stream=io.BytesIO(request.data), filename=filename, content_type=mimetype ) # Find media manager entry = new_upload_entry(request.user) entry.media_type = IMAGE_MEDIA_TYPE return api_upload_request(request, file_data, entry) return json_error("Not yet implemented", 501)
def test_api_usd_file_supported(app, client): avocado = os.path.join('tests/assets/Avocado.glb') file = FileStorage( stream=open(avocado, 'rb'), filename='Avocado.glb', content_type='glb' ) res = client.post( '/api/usd', data = { 'file': file }, content_type='multipart/form-data' ) assert res.status_code == 200
def test_when_update_post_then_success( upload_mock, session, normal_user_factory, article_factory, attachment_factory, add_and_commit, ): user = normal_user_factory(Region=True, UserProfile=True, Post=True) add_and_commit([user]) attachment = attachment_factory(post_id=user.post[0].id) add_and_commit([attachment]) article = article_factory(post_id=user.post[0].id) add_and_commit([article]) # 실제 업로드 확인하려면 아래 경로에 이미지 첨부하고 patch 데코레이터 제거한 뒤 실행. file = FileStorage( stream=io.BytesIO(b"aaa"), filename="C:/project/rabbit/app/extensions/utils/a.jpg", content_type="multipart/form-data", ) dto = UpdatePostDto( post_id=user.post[0].id, user_id=user.id, title="떡볶이 같이 먹어요", body="new body", region_group_id=1, type="article", is_comment_disabled=True, amount=10, unit=PostUnitEnum.UNIT.value, price_per_unit=10000, status=PostStatusEnum.SELLING.value, file_type=AttachmentEnum.PICTURE.value, files=[file], ) post_entity = UpdatePostUseCase().execute(dto=dto).value assert post_entity.title == dto.title assert post_entity.body == dto.body assert post_entity.is_comment_disabled == dto.is_comment_disabled assert isinstance(post_entity.attachments, list)
def test_node_parser(): """Test node parser.""" with (Path(__file__).parent / "files/npm-list.json").open('rb') as f: direct_dependencies, transitive_dependencies = \ NodeParser.parse_output_files([FileStorage(f)]) assert direct_dependencies is not None assert transitive_dependencies is not None assert direct_dependencies == { "npm:github-url-to-object:4.0.4", "npm:lodash:4.17.10", "npm:normalize-registry-metadata:1.1.2", "npm:revalidator:0.3.1", "npm:semver:5.5.1" } assert transitive_dependencies == { "npm:is-url:1.2.4", "npm:semver:5.5.1" }
def _test_post(self): #with test_recipients data = os.path.join(stc_path, "email_data_valide.json") file_to_transfer = FileStorage(stream=open(data, "rb"), content_type="application/json") r = self.current_client.post(f'/{self.version}/email', data={ "template_id": self.template_id, "respondents": file_to_transfer, "test_recipients": "[email protected];[email protected]" }, content_type="multipart/form-data") self.assertEqual(r.status_code, 200)
def upload_pba_file(file_storage: FileStorage, is_linux=True): """ Uploads PBA file to island's file system :param request_: Request object containing PBA file :param is_linux: Boolean indicating if this file is for windows or for linux :return: filename string """ filename = secure_filename(file_storage.filename) file_contents = file_storage.read() PostBreachFilesService.save_file(filename, file_contents) ConfigService.set_config_value( (PBA_LINUX_FILENAME_PATH if is_linux else PBA_WINDOWS_FILENAME_PATH), filename) return filename
def get_response( self, url, form_data ): """Helper to get a request with a file""" with open( JPG_FILE_PATH, 'rb' ) as file_pointer: jpg_file_storage = FileStorage( stream=file_pointer, filename=JPG_FILE_NAME, content_type='image/jpeg' ) form_data[ 'campaign_photo' ] = jpg_file_storage response = self.test_client.put( url, data=form_data, content_type='multipart/form-data', headers=self.headers ) return response
def test_wrong_files_error_new_run_3(self, client): with app.test_request_context(): dummy_file = FileStorage(filename='data.txt') form = LoadDataForm(survey_file=dummy_file, shift_file=dummy_file, non_response_file=dummy_file, unsampled_file=dummy_file, tunnel_file=dummy_file, sea_file=dummy_file, air_file=dummy_file) res = client.post('/new_run/new_run_3', data=form.data, follow_redirects=True) assert res.status_code == 200 assert b'This field is required.' in res.data assert b'Select process variables' not in res.data
def parse_parts(self, file, boundary, content_length): """Generate `('file', (name, val))` and `('form', (name ,val))` parts. """ in_memory = 0 for ellt, ell in self.parse_lines(file, boundary, content_length): if ellt == _begin_file: headers, name, filename = ell is_file = True guard_memory = False filename, container = self.start_file_streaming( filename, headers, content_length) _write = container.write elif ellt == _begin_form: headers, name = ell is_file = False container = [] _write = container.append guard_memory = self.max_form_memory_size is not None elif ellt == _cont: _write(ell) # if we write into memory and there is a memory size limit we # count the number of bytes in memory and raise an exception if # there is too much data in memory. if guard_memory: in_memory += len(ell) if in_memory > self.max_form_memory_size: self.in_memory_threshold_reached(in_memory) elif ellt == _end: if is_file: container.seek(0) yield ('file', (name, FileStorage(container, filename, name, headers=headers))) else: part_charset = self.get_part_charset(headers) yield ('form', (name, _decode_unicode(''.join(container), part_charset, self.errors)))
def test_send_submit(): client = InternalRmatics() client.service_url = CLIENT_SERVICE_URL client.client = Mock() data = {'lang_id': 1, 'user_id': 2, 'statement_id': 3} file = FileStorage(io.BytesIO(b'sample data'), filename='test.cpp', content_type='application/pdf') client.send_submit(file, data['user_id'], PROBLEM_ID, data['statement_id'], data['lang_id']) client.client.post_data.assert_called_with( f'{client.service_url}/problem/trusted/{PROBLEM_ID}/submit_v2', json=data, files={'file': file.stream}, silent=True)
def test_create_item_pictures__failure_non_existing_item(self): user = self.create_user(superuser=True) test_image_path = os.path.join('.', 'tests', 'images', 'test_image.jpg') picture_data = { 'title': 'Example image', 'file': FileStorage(open(test_image_path, 'rb')), } resp = self.open_with_auth('/items/{}/pictures'.format(uuid.uuid4), 'post', user.email, 'p4ssw0rd', data=picture_data, content_type='multipart/form-data') assert resp.status_code == NOT_FOUND
def test_SegmentMainService(self): with app.test_client() as c: my_file = FileStorage( stream=open("fileTest.txt", "rb"), ), resp = c.get( "/glexSegment", data={ "file": my_file, }, content_type="multipart/form-data" ) respones = json.loads(resp.data) assumpResults = [['ทดสอบ', 2], ['การ', 2], ['ตัด', 1], ['123', 4], [' ', 5], ['/', 5], ['*', 5], ['-', 5], [' ', 5], ['test', 3], [' ', 5], ['[+-\\]', 6]] self.assertTrue(respones['status'] == "ok","please check glex service make sure started") self.assertEqual(assumpResults,respones['results']) self.assertTrue(respones['dictName'])
def __get_files(info: blackboard.SubmissionInfo) -> t.List[FileStorage]: files = [] for blackboard_file in info.files: if isinstance(blackboard_file, blackboard.FileInfo): name = blackboard_file.original_name stream = open( safe_join(tmpdir, blackboard_file.name), mode='rb' ) else: name = blackboard_file[0] stream = io.BytesIO(blackboard_file[1]) if name == '__WARNING__': name = '__WARNING__ (User)' files.append(FileStorage(stream=stream, filename=name)) return files
def test_resource_with_upload(self, mock_uploads_enabled, mock_open, send_file): # this test data is based on real observation using a browser res = { u'clear_upload': u'', u'format': u'PNG', u'url': u'https://example.com/data.csv', u'description': u'', u'upload': FileStorage(filename=u'data.csv', content_type=u'CSV'), u'package_id': u'dataset1', u'id': u'8a3a874e-5ee1-4e43-bdaf-e2569cf72344', u'name': u'data.csv' } res_upload = ResourceUpload(res) eq_(res_upload.filesize, 0) eq_(res_upload.filename, u'data.csv')
def test_create_item_picture__failure_user_is_not_superuser(self): user = self.create_user() test_image_path = os.path.join('.', 'tests', 'images', 'test_image.jpg') item = self.create_item() picture_data = { 'title': 'Example image', 'file': FileStorage(open(test_image_path, 'rb')), } resp = self.open_with_auth('/items/{}/pictures'.format(item.uuid), 'post', user.email, 'p4ssw0rd', data=picture_data, content_type='multipart/form-data') assert resp.status_code == UNAUTHORIZED
def test_resource_with_upload(self, ckan_config, monkeypatch, tmpdir): monkeypatch.setitem(ckan_config, u'ckan.storage_path', str(tmpdir)) # this test data is based on real observation using a browser res = { u'clear_upload': u'', u'format': u'PNG', u'url': u'https://example.com/data.csv', u'description': u'', u'upload': FileStorage(filename=u'data.csv', content_type=u'CSV'), u'package_id': u'dataset1', u'id': u'8a3a874e-5ee1-4e43-bdaf-e2569cf72344', u'name': u'data.csv' } res_upload = ResourceUpload(res) assert res_upload.filesize == 0 assert res_upload.filename == u'data.csv'
def test_create_task_ndex_param_not_set(self): try: # try with empty parameters pdict = {} pdict['remoteip'] = '1.2.3.4' pdict[nbgwas_rest.ALPHA_PARAM] = 0.5 pdict['protein_coding'] = 'hg19' snpfile = FileStorage(stream=io.BytesIO(b'hi there'), filename='yo.txt') pdict[nbgwas_rest.SNP_LEVEL_SUMMARY_PARAM] = snpfile nbgwas_rest.create_task(pdict) self.fail('Expected exception') except Exception as e: self.assertEqual(str(e), nbgwas_rest.NDEX_PARAM + ' is required')
def test_a_scan(self): """Test file upload and scan.""" testzip = FileStorage( stream=open('static/tests/test_assets.zip', 'rb'), filename='test_assets.zip', content_type='application/zip', ) response = self.app.post('/upload/', content_type='multipart/form-data', data={'file': testzip}, follow_redirects=True) self.assertEqual(response.status_code, 200) self.assertEqual(response.is_json, True) self.assertEqual(response.json, { 'status': 'success', 'url': f'scan/{VALID_HASH}' })
def test_crop(self): """Test UPLOADER crop works.""" u = Uploader() size = (100, 100) im = Image.new('RGB', size) folder = tempfile.mkdtemp() u.upload_folder = folder im.save(os.path.join(folder, 'image.png')) coordinates = (0, 0, 50, 50) file = FileStorage(filename=os.path.join(folder, 'image.png')) with patch('pybossa.uploader.Image', return_value=True): err_msg = "It should crop the image" assert u.crop(file, coordinates) is True, err_msg with patch('pybossa.uploader.Image.open', side_effect=IOError): err_msg = "It should return false" assert u.crop(file, coordinates) is False, err_msg
def test_get(self): # create new mail job to test an id to perform the test data = os.path.join(stc_path, "mail_data_valide.json") file_to_transfer = FileStorage(stream=open(data, "rb"), content_type="application/json") r = self.current_client.post(f'/{self.version}/mail', data={ "template_id": self.template_id, "respondents": file_to_transfer, }, content_type="multipart/form-data") self.assertEqual(r.status_code, 200) data = json.loads(r.data) id = data.get("id") r_mail = self.current_client.get(f'/{self.version}/mail/{id}') self.assertEqual(r_mail.status_code, 200)
def process(self, image: FileStorage) -> str: assert image.filename, 'Image filename is required' filename = '{time}_{name}'.format(time=str(int(time.time())), name=secure_filename(image.filename)) path = self.create_path(filename) image.save(path) image = Image.open(path) image.thumbnail((360, 360)) image.save(path) return filename
def _get_csv_data_from_request(self, csv_filename): if csv_filename is None: msg = ("Not a valid csv file for import") raise BulkImportException(gettext(msg), 'error') datafile = get_import_csv_file(csv_filename) csv_file = FileStorage(io.open( datafile.name, encoding='utf-8-sig')) #utf-8-sig to ignore BOM if csv_file is None or csv_file.stream is None: msg = ("Unable to load csv file for import, file {0}".format( csv_filename)) raise BulkImportException(gettext(msg), 'error') csv_file.stream.seek(0) csvcontent = io.StringIO(csv_file.stream.read()) csvreader = unicode_csv_reader(csvcontent) return list(self._import_csv_tasks(csvreader))
def do_post(): if (len(request.files) > 0): meas_file = request.files['file'] plot = make_plot_of_meas_file(meas_file) app.config['dry_file'] = meas_file.filename name_root = meas_file.filename.split('.')[0] app.config['synth_file'] = name_root + '_synth.wav' app.config['mode_file'] = name_root + '.waterbottle' meas_file.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(meas_file.filename))) return render_template('bespoke.html', measurement=plot, actual_audio='/uploads/'+app.config['dry_file']) else: meas_file = FileStorage(filename=os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(app.config['dry_file']))) plot1 = make_plot_of_meas_file(meas_file.filename) plot2 = do_modal_analysis(meas_file.filename) return render_template('bespoke.html', measurement=plot1, actual_audio='/uploads/'+app.config['dry_file'], synthesized=plot2, synth_audio='/uploads/'+app.config['synth_file']) return render_template("bespoke.html")
def saveFile(stream, filename, path_conf): random_seq = str(uuid.uuid4())[:8] full_filename = secure_filename(filename) filename, file_extension = os.path.splitext(full_filename) filenameFs = f'{filename}---{random_seq}{file_extension}' pathFile = os.path.join(path_conf, filenameFs) absPath = os.path.abspath(pathFile) try: FileStorage(stream).save(absPath) app_log.info( f'file success save, filename={full_filename}, filenameFs={filenameFs}' ) return absPath, filenameFs except Exception as e: error_log.error(format_exc(type(e), e)) raise
def test_upload_thumbnail(self): thumbnail = { "mimetype": "image/jpeg", "url": "http://localhost/projects/video_id/raw/thumbnails/preview" } with requests_mock.mock() as mock: mock.post('http://localhost/projects/video_id/thumbnails', json=thumbnail) req = {'file': FileStorage(BytesIO(b'abcdef'), 'image.jpeg')} res = self.video_edit.on_replace(req, {'project': { '_id': 'video_id' }}) self.assertEqual( res['renditions']['thumbnail']['href'], 'http://localhost/projects/video_id/raw/thumbnails/preview') self.assertEqual(res['renditions']['thumbnail']['mimetype'], 'image/jpeg')
def test_rackspace_uploader_upload_correct_purgin_first_file( self, mock, mock2): """Test RACKSPACE UPLOADER upload file purging first file works.""" with patch('pybossa.uploader.rackspace.pyrax.cloudfiles') as mycf: mycf.upload_file.return_value = True mycf.get_object.side_effect = True u = RackspaceUploader() u.init_app(self.flask_app) file = FileStorage(filename='test.jpg') err_msg = "Upload file should return True" assert u.upload_file(file, container='user_3') is True, err_msg calls = [ call.get_container('user_3'), call.get_container().get_object().delete(), call.get_container().get_object('test.jpg') ] print mycf.mock_calls mycf.assert_has_calls(calls, any_order=True)
def test_Upload_Success(self): req = Request req.method = 'POST' req.files = MultiDict([('file', FileStorage(filename=u'img.png', content_type='image/jpeg'))]) # bp = Blueprint('testBP', __name__) upload(req) fileLoc = os.path.join(dirname(dirname(dirname(__file__))), UPLOAD_FOLDER, req.files['file'].filename) try: unittest.assertTrue(os.path.exists(fileLoc)) except: pass finally: if os.path.exists(fileLoc): os.remove(fileLoc)
def test_upload_xlsx_to_intake_bucket(monkeypatch): trial_id = "test-trial" assay_type = "wes" xlsx = FileStorage(filename="metadata.xlsx") _get_bucket = MagicMock() _get_bucket.return_value = bucket = MagicMock() bucket.blob.return_value = blob = MagicMock() monkeypatch.setattr("cidc_api.shared.gcloud_client._get_bucket", _get_bucket) url = upload_xlsx_to_intake_bucket(EMAIL, trial_id, assay_type, xlsx) blob.upload_from_file.assert_called_once() assert url.startswith( "https://console.cloud.google.com/storage/browser/_details/cidc-intake-staging-" ) assert f"/{trial_id}/{assay_type}" in url assert url.endswith(".xlsx")
def setUp(self): super(SaveAttachmentTest, self).setUp() (filename, file_stream) = get_attachment() self.attachment = FileStorage(stream=file_stream, filename=filename)
def seed(): """ Seed function to populate the database with initial values. """ try: if User.query.first() and not app.config["DEBUG"]: return # dev mode: always seed db on restart except: pass print("Create Tables...") if not app.config["UPLOAD_FOLDER"]: # pragma: no cover raise RuntimeError("No upload folder specified!") if os.path.exists(app.config["UPLOAD_FOLDER"]): shutil.rmtree(app.config["UPLOAD_FOLDER"]) os.makedirs(app.config["UPLOAD_FOLDER"]) db.drop_all() db.create_all() print("Seeding...") # Kunden seeden patient_datasets = ( { "username": "******", "name": "Siegrun Kreft", "birthday": "19.07.1963", "gender": "weiblich" }, { "username": "******", "name": "Lena Laengerich", "birthday": "12.04.1983", "gender": "weiblich" }, { "username": "******", "forename": "Peter", "name": "Peter Becker" }, { "username": "******", "name": "Lilo Meier" }, { "username": "******", "name": "Hardmut Meier" }, { "username": "******", "name": "Peter Richter" }, { "username": "******", "name": "Harald Himmelkütter" }, { "username": "******", "name": "Lisa Weigle" }, { "username": "******", "name": "Günter Kunert" }, { "username": "******", "name": "Viktoria Hansen" }, { "username": "******", "name": "Lili Brecht" }, ) patients = [] for i in range(len(patient_datasets)): patients.append( Resident( username=patient_datasets[i]["username"], pw_hash=generate_password_hash('123456'), name=patient_datasets[i]["name"], birthday=patient_datasets[i].get("birthday", ""), email="kunde" + str(i) + "@example.com", ) ) for patient in patients: db.session.add(patient) admin = Administrator( username="******", name="Administrator", pw_hash=generate_password_hash('admin') ) db.session.add(admin) with open(seed_dir("pictures/header_wrap_picture.png"), "rb") as f: access_token = 'pictures' file = FileStorage(f, filename="header_wrap_picture.png") os.mkdir(os.path.join(app.config["UPLOAD_FOLDER"], access_token)) filename = access_token + "/" + secure_filename(file.filename) file.save(os.path.join(app.config["UPLOAD_FOLDER"], filename)) f = filename wrap = Picture(name="header_wrap_picture", image=f) db.session.add(wrap) db.session.commit() announcements_database = ( { "title": "Freibier am Samstag!", "content": "Liebe Breulianer, im Zuge des Neuenwochenendes werden wir an diesem Samstag (27.09.) die Bar öffnen, damit man sich schon einmal kennenlernen kann. Starten werden wir spätestens gegen 21 Uhr. Es wird auch Freibier geben, also kommt alle und zahlreich! Eure Tutoren, Lukas und Jules" }, { "title": "Liturgieplan Juli 2014", "content": "Gottesdienste in der Hauskapelle „Verklärung Christi“ im Juli 2014 Dienstag 1. Juli 7:00 Uhr Heilige Messe L: Am 3,1-8; 4,11-12 Ev: Mt 8,23-27 Mittwoch Mariä Heimsuchung 2. Juli 20:30 Uhr Heilige Messe vom FestL: Röm 12,9-16bEv: Lk 1,39-56 Donnerstag 3. Juli 22:00 Uhr22:30 Uhr Eucharistische AnbetungKomplet Dienstag 8. Juli 7:00 Uhr Heilige MesseL: Hos 8,4-7.11-13Ev: […]" }, { "title": "KSHG Turnier", "content": "Liebe Mitbewohner, während wir uns heute Abend ab- Achtung!- 18:30 Uhr im Breulcup beim Fußball messen, findet am Sonntag um 11 Uhr das traditionsreiche KSHG-Fußballturnier am Bistumsplatz an der Anette Allee 43 (vgl. Weg vom Breul aus) statt. Es wäre schön, wenn dort nicht nur die Fußball-, sondern auch die Breulbegeisterten vorbeischauen würden, um unsere […]" }, { "title": "Maitour", "content": "Hallo Jungs, auch wenn das Wetter für morgen nicht allzu gut angesagt ist, werden wir, die Tutoren der Burse und des Breul, ein Programm anbieten. Wir treffen uns um 12 Uhr auf dem großen 400er Balkon (oder in der Nähe) und starten unsere Rallye wenn die Burse um 14 Uhr dazu gestoßen ist. Ein Regenplan […]" } ) announcements =[] for i in range(len(announcements_database)): announcements.append( Announcement( title=announcements_database[i]["title"], content=announcements_database[i]["content"] ) ) announcements.append( Announcement( title="Lorem Impsum", content=announcements_database[3]["content"], public=1 )) for announcement in announcements: db.session.add(announcement) db.session.commit() items_database = ( { "name": "Bier", "price": 1 }, { "name": "Weizen", "price": 1 }, { "name": "Mischbier", "price": 1 }, { "name": "Wasser", "price": 0.8 }, { "name": "Cola", "price": 1.1 }, { "name": "Pizza", "price": 1.8 }, { "name": "Chips", "price": 0.8 }, { "name": "Salzstangen", "price": 0.6 }, { "name": "Mettentchen", "price": 1 } ); items =[] for i in range(len(items_database)): items.append( Item( name=items_database[i]["name"], price=items_database[i]["price"] ) ) for item in items: db.session.add(item) db.session.commit() bar_inventory = [] for item in items: bar_inventory.append( BarInventory( item=item, amount=10, date="12.12.2014" ) ) for item in bar_inventory: db.session.add(item) db.session.commit() barcharge = BarCharge(resident_id=1, done=True) db.session.add(barcharge) db.session.commit() blub = SoldItemBar(barCharge=barcharge, item=items[1], amount=5) db.session.add(blub) db.session.commit() today = date.today() bar_date = today calendar = [] for i in range(1,31): bar_date=bar_date.replace(day=i) calendar.append( BarCalendar(date=bar_date, bar_charge_id=1) ) for charge in calendar: db.session.add(charge) db.session.commit() print("Complete!")
def ueditor_upload(): """ueditor接口""" mimetype = 'application/json' result = {} action = request.args.get('action') # 解析JSON格式的配置文件 with open('static/ueditor/php/config.json') as fp: try: # 删除 `/**/` 之间的注释 CONFIG = json.loads(re.sub(r'\/\*.*\*\/', '', fp.read())) except: CONFIG = {} # 初始化时,返回配置文件给客户端 if action == 'config': result = CONFIG # 上传文件 elif action in ('uploadimage', 'uploadvideo', 'uploadfile'): # 图片、文件、视频上传 # if action == 'uploadimage': # fileName = CONFIG.get('imageFieldName') if len(request.files) > 1: result = {'state': '不支持多个文件同时上传'} else: f = request.files.values()[0] file_id = save_gfs_file(resource_gfs, f) f.close() result = { "state": "SUCCESS", "url": resource_gfs_url(file_id), "title": f.filename, "original": f.filename, # "type": "." + f.filename.split('.')[-1], # "size": 7819 } # 涂鸦图片上传 elif action == 'uploadscrawl': base64data = request.form['upfile'] # 这个表单名称以配置文件为准 img = base64.b64decode(base64data) buff = StringIO() buff.write(img) buff.seek(0) # tricky save_gfs_file only accept FileStorage object or something like file_storage = FileStorage(filename='', content_type='image/png', content_length=buff.len, stream=buff) file_id = save_gfs_file(resource_gfs, file_storage) file_storage.close() result = { "state": "SUCCESS", "url": resource_gfs_url(file_id), "title": file_id, "original": file_id } # 抓取远程图片 elif action == 'catchimage': sources = request.form.getlist('source[]') _list = [] for source in sources: f = urllib2.urlopen(urllib2.Request(source, headers={'User-agent': 'Mozilla/5.0'})) buff = StringIO() buff.write(f.read()) buff.seek(0) # tricky save_gfs_file only accept FileStorage object or something like file_storage = FileStorage(headers=f.headers, stream=buff) file_id = save_gfs_file(resource_gfs, file_storage) f.close() file_storage.close() _list.append({ "url": resource_gfs_url(file_id), "source": source, "state": "SUCCESS" }) result = { "state": "SUCCESS", "list": _list } else: result = {'state': '不能识别的action: %s' % action} # todo: 回调参数, 这个不知道有没有用到,从别处拷过来的 if 'callback' in request.args: callback = request.args.get('callback') if re.match(r'^[\w_]+$', callback): result = '%s(%s)' % (callback, result) mimetype = 'application/javascript' res = make_response(result) res.mimetype = mimetype res.headers['Access-Control-Allow-Origin'] = '*' res.headers['Access-Control-Allow-Headers'] = 'X-Requested-With,X_Requested_With' return res else: result = {'state': 'callback参数不合法'} # return jsonify(result) # return json.dumps(result) result = json.dumps(result) # print result res = make_response(result) res.mimetype = 'application/json' res.headers['Access-Control-Allow-Origin'] = '*' res.headers['Access-Control-Allow-Headers'] = 'X-Requested-With,X_Requested_With' return res