def create(self, user, **kwargs): kwargs["uuid"] = generate_key() attachment = Attachment.create(user=user, **kwargs) return attachment
def upload_attachment(): file = request.files.get('file') thumb = bool(request.args.get('thumb', False)) if not file: raise JsonOutputException('请选择要上传的文件') file_type = request.form.get('type', '') data = upload(file, thumb) if data.get('status') is True: attachment = Attachment(name=data.get('original', ''), url=data.get('url', ''), user_id=g.user.id, file_type=file_type) attachment.save() #attachment.id return {'code': 0, 'data': [attachment.url]} raise JsonOutputException('上传失败')
def delete(self, _id): attachment = Attachment.select().where(Attachment.id == _id).get() attachment.delete_instance() return True
def _store_attachment(logger, data, message_id): ''' Creates new Attachment entry if Message has already been created ''' logger.info('Creating Attachment.') a = Attachment(message_id=message_id, name=data['name']) try: _add(a) except Exception as e: raise Exception(e)
def test_add_recipient(self): message_id = '1578083234-893239-2956-1311577-1' name = 'Attachment1.docx' a = Attachment(message_id=message_id, name=name) db.session.add(a) db.session.commit() db.session.refresh(a) a = Attachment.query.filter_by(id=a.id).first() self.assertTrue(a) a = Attachment.query.filter_by(id=-1).first() self.assertFalse(a)
def post(self): attachment = Attachment() args = parser.parse_args() merge(attachment, args) with safe_session(db): db.session.add(attachment) return {Const.MESSAGE_KEY: '交付物创建成功'}
def post(self): if current_user.is_authenticated: args = attachments_args.parse_args() file = args['file'] file_name = args['file_name'] file_size = args['file_size'] file_type = args['file_type'] file_id = args['file_id'] file_extension = args['file_extension'] recipient = args['receiver'] sender = current_user.username file.save( os.path.join(current_app.root_path, 'static', 'uploads', '{}_{}'.format(sender, file_id))) recipient_user = User.query.filter_by(username=recipient).first() friendship_chat = Friendship.query.filter( (Friendship.friend_a_id == current_user.id) & (Friendship.friend_b_id == recipient_user.id)).first() room = friendship_chat.chatKey # Saving to message table message = Message(message='', seen=False, created_at=datetime.datetime.now(), senderID=current_user.id, reciverID=recipient_user.id) attachment = Attachment(attachment_id=file_id, type=file_type, message=message, file_name=file_name) db.session.add(message) db.session.add(attachment) db.session.commit() try: socketio.emit('attachments', { 'file': file.read(), 'type': file_type, 'extension': file_extension, 'title': file_name, 'size': file_size }, room=room, namespace='/api/chat', skip_sid=session['sid']) except KeyError: return {'status': "KeyError: Couldn't send attachments"} return {'status': "succesful"} else: return {'status': "Error 401: Unauthorized"}
def get_attachments(message_id): ''' Retrieve a collection of all attachments ''' page = request.args.get('page', 1, type=int) per_page = min(request.args.get('per_page', 10, type=int), 100) m = Message.query.get_or_404(message_id) data = Attachment.to_collection_dict(m.attachments, page, per_page, 'api.get_attachments', message_id=message_id) return jsonify(data)
def create_attachment(): ''' Create a new attachment ''' data = request.get_json() or {} if 'message_id' not in data: return bad_request('must include message_id') if 'name' not in data: return bad_request('must include name') if Attachment.query.filter_by(message_id=data['message_id'], name=data['name']).first(): return bad_request('message already has that attachment name') attachment = Attachment() attachment.from_dict(data) db.session.add(attachment) db.session.commit() response = jsonify(attachment.to_dict()) response.status_code = 201 response.headers['Location'] = url_for('api.get_attachment', attachment_id=attachment.id) return response
def read_by_order(self, order_id): result = list() order_attachments = OrderAttachment.select().where( OrderAttachment.order_id == order_id) for order_attachment in order_attachments: attachment = Attachment.select().where( Attachment.id == order_attachment.attachment_id).get() result.append(attachment) return result
def get_attachments(self, _id): result = list() order = self.read(_id) order_attachments = OrderAttachment.select().where( OrderAttachment.order_id == order.id).get() for order_attachment in order_attachments: attachment = Attachment.select().where( Attachment.id == order_attachment.attachment_id).get() result.append(attachment) return result
def edit_publication(publication=None): form = PublicationUploadForm(obj=publication) if publication: ensureEditable(publication) if form.validate_on_submit(): if not publication: publication = Publication(author_id=current_user.id, url_slug=generate_slug(form.title.data)) db.session.add(publication) publication.title = form.title.data publication.pub_year = form.pub_year.data publication.authors = form.authors.data publication.journal = form.journal.data publication.link = form.link.data publication.abstract = form.abstract.data publication.published = True for file in form.files.data: if file == '': continue f = File.fromUpload(file) db.session.add(f) publication.files.append(Attachment(file=f, name=file.filename)) db.session.commit() return redirect(url_for('edit_publication', publication=publication)) data = { 'publication': publication.serialize() if publication else None, 'form': form.serialize(), 'csrf_token': g.csrf_token } return render_vue(data, title='Edit' if publication else 'Create', menu='publications')
def populate(): print("Criando as disciplinas básicas...") portugues = Disciplina.create("Português") matemática = Disciplina.create("Matemática") historia = Disciplina.create("História") geografia = Disciplina.create("Geografia") ciencias = Disciplina.create("Ciências") print("Criando as disciplinas para Prova Brasil...") portugues_prova_brasil = Disciplina.create("Português", True) matemática_prova_brasil = Disciplina.create("Matemática", True) disciplinas = [ portugues, matemática,historia,geografia,ciencias ] disciplinas_prova_brasil = [ portugues_prova_brasil, matemática_prova_brasil ] print("Início do loop de questões do super reforço...") for disciplina in disciplinas: for serie in series: for bim in bimestres: for index in range(5): aula = Aula.create( disciplina, "Assunto_{0}{1}{2}{3}".format(disciplina.nome, serie, bim, index), serie, bim ) Attachment.create(aula, 'http://localhost.com/v', '') for ex in range(5): exercicio = Exercicio.create(aula, "Aula {0}_{1}".format(aula.assunto, ex)) Alternativa.create(exercicio, 'enunciado', '', True) Alternativa.create(exercicio, 'enunciado', '', False) Alternativa.create(exercicio, 'enunciado', '', False) Alternativa.create(exercicio, 'enunciado', '', False) print('.') print("Início do loop de questões da prova brasil...") for disciplina in disciplinas_prova_brasil: for serie in series: for index in range(5): aula = Aula.create( disciplina, "Assunto_{0}{1}{2}{3}".format(disciplina.nome, serie, 1, index), serie, 1 ) Attachment.create(aula, 'http://localhost.com/v', '') for ex in range(5): exercicio = Exercicio.create(aula, "Aula {0}_{1}".format(aula.assunto, ex)) Alternativa.create(exercicio, 'enunciado', '', True) Alternativa.create(exercicio, 'enunciado', '', False) Alternativa.create(exercicio, 'enunciado', '', False) Alternativa.create(exercicio, 'enunciado', '', False) print('.')
def upload(): # 附件所属文章或笔记的id id = int(request.form['id']) code = int(request.form['code']) # 处理文件大小 filesize = int(request.headers['content-length']) / 1024 if filesize < 1024: filesize = format(filesize, '.2f') + 'Kb' elif filesize > 1024 and filesize < 1024 * 1024: filesize = format(filesize, '.2f') + 'Mb' # 处理文件名 origin = str(request.files['file']).split(' ')[1].split("'")[1] filename = str( request.files['file']).split(' ')[1].split("'")[1].split('.')[0] fileext = str( request.files['file']).split(' ')[1].split("'")[1].split('.')[1] # 文件更名并存储 file = filename + datetime.now().strftime("%Y%m%d%H%M%S") + '.' + fileext basepath = os.path.join( os.path.abspath(os.path.dirname(__file__))[0:-4], 'static/uploads') current_year = datetime.now().strftime('%Y') current_year_path = os.path.join(basepath, current_year) print(current_year_path) current_month = datetime.now().strftime('%m') current_month_path = os.path.join(current_year_path, current_month) print(current_month_path) if os.path.exists(current_year_path): if os.path.exists(current_month_path): print('存在' + current_month + '文件夹') else: os.mkdir(current_month_path) print('创建' + current_month + '文件夹') else: os.makedirs(current_month_path) print('创建' + current_month_path + '文件夹') # 一经部署,图片存储后的本地路径就固定了,迁移博客时需要确保博客根目录新存放路径与原路径一致,否则旧图片将无法正常删除,虽然新图片不受影响 local = os.path.join(current_month_path, file) request.files['file'].save(local) # 文件url # url = current_app.config['FLASKY_HOST'] + url_for('static',filename='uploads/' + current_year + '/' + current_month + '/' + file) # 采用相对路径 url = '/' + current_year + '/' + current_month + '/' + file # 数据库操作 if code == 0: attachment = Attachment(filename=origin, securename=file, filesize=filesize, date=datetime.now(), local=local, url=url, post_id=id) else: attachment = Attachment(filename=origin, securename=file, filesize=filesize, date=datetime.now(), local=local, url=url, note_id=id) db.session.add(attachment) db.session.commit() # 返回结果 result = { "code": 0, "msg": "", "data": { "filename": origin, "securename": file, "size": filesize, "src": url } } return jsonify(result)
def read(self, _id): attachment = Attachment.select().where(Attachment.id == _id).get() return attachment
def read_by_uuid(self, uuid): attachment = Attachment.select().where(Attachment.uuid == uuid).get() return attachment
def edit_scan(scan=None): form = ScanUploadForm(obj=scan) if scan: ensureEditable(scan) if not form.geologic_age.data: form.geologic_age.data = scan.geologic_age if not form.ontogenic_age.data: form.ontogenic_age.data = scan.ontogenic_age if not form.elements.data: form.elements.data = scan.elements # Get the records for the currently selected publications pubs = Publication.query.filter( Publication.author_id == current_user.id).all() form.publications.choices = [(pub, pub.title) for pub in pubs] if request.method == 'POST': if scan == None: scan = Scan(author_id=current_user.id, ) db.session.add(scan) # Make sure whatever publications are selected pass validation form.publications.choices = [(pub, pub.title) for pub in form.publications.data] # TODO: Restrict list of uploadable file types # Save upload to temporary file if form.file.data: app.logger.warn('call zip_upload') zipFile = zip_upload(form.file.data) app.logger.warn('zip_upload done') scan.source = zipFile db.session.add(zipFile) app.logger.warn('zip added to session') if scan.url_slug == None: scan.url_slug = generate_slug(form.scientific_name.data) scan.scientific_name = form.scientific_name.data scan.alt_name = form.alt_name.data scan.specimen_location = form.specimen_location.data scan.specimen_id = form.specimen_id.data scan.specimen_url = form.specimen_url.data scan.description = form.description.data scan.publications = form.publications.data scan.tags = form.geologic_age.data + form.ontogenic_age.data + form.elements.data gbif_id = form.gbif_id.data if gbif_id and gbif_id != scan.gbif_id: from app.gbif import pull_tags scan.gbif_id = gbif_id tags = pull_tags(gbif_id) tagIds = [tag.id for tag in tags] existingTags = Taxonomy.query.filter(Taxonomy.id.in_(tagIds)).all() existingTagIds = [tag.id for tag in existingTags] scan.taxonomy = existingTags for tag in tags: if tag.id in existingTagIds: continue db.session.add(tag) scan.taxonomy.append(tag) for file in form.attachments.data: if isinstance(file, Attachment): continue import string import random import magic # Take the filename as the label and generate a new, safe filename label = file.filename filename = secure_filename(file.filename) + '.png' fileModel = File.fromBinary(filename, file.stream) if (fileModel.mime_type != 'image/png'): form.stills.errors.append('Stills must be png files') else: file.save(fileModel.getAbsolutePath()) attachment = Attachment(name=label, file=fileModel) db.session.add(attachment) scan.attachments.append(attachment) form_valid = True if form.published.data: form_valid = form.validate() if not scan.source: form_valid = False form.file.errors.append('A scan file is required') if not scan.attachments: form_valid = False form.stills.errors.append('A still is required') if form_valid: scan.published = True else: scan.published = False app.logger.warn('check form valid') if form_valid: app.logger.warn('form valid, continue') db.session.commit() if not request.args.get('noredirect'): return redirect( request.args.get('redirect') or url_for('scan', scan=scan)) data = { 'form': form.serialize(), 'scan': scan.serialize() if scan else None, 'csrf_token': g.csrf_token } return render_vue(data, title='Edit' if scan else 'Upload New', menu='library')
def delete(self, slug, id): attachment = Attachment.objects(id=id).first() attachment.delete() return jsonify({'success':True})
def action_upload_file(): if request.method == 'POST': upload_file = request.files.get('upload_file') if not upload_file: return make_response( jsonify({ "code": app.config.get('RESPONSE_UPLOAD_ERROR_CODE'), "message": app.config.get('RESPONSE_UPLOAD_ERROR_MESSAGE') })) file_name = upload_file.filename file_type = os.path.splitext(file_name)[-1] if not file_type.lower() in app.config.get('FILE_ALLOWED'): return make_response( jsonify({ "code": app.config.get('RESPONSE_UPLOAD_NOT_ALLOW_CODE'), "message": app.config.get('RESPONSE_UPLOAD_NOT_ALLOW_MESSAGE') })) upload_path = get_upload_path() if not os.path.exists(upload_path): os.makedirs(upload_path, 0o777) tmp_file_name = "{}{}".format(get_random(), file_type) upload_file.save(os.path.join(upload_path, tmp_file_name)) visit_path = os.path.join("attach", datetime.datetime.now().strftime("%Y-%m-%d"), tmp_file_name) attach_size = os.path.getsize(os.path.join(upload_path, tmp_file_name)) upload = Uploadfile(upload_name='博客文章附件', upload_path=upload_path, upload_type=file_type, upload_size=attach_size, upload_busi='article_attachment', upload_real=file_name, upload_saved=tmp_file_name, upload_visit=visit_path, upload_creator=session.get('username')) try: db.session.add(upload) db.session.commit() except Exception as e: app.logger.exception(e) return make_response( jsonify({ "code": app.config.get('RESPONSE_SAVE_ERROR_CODE'), "message": app.config.get('RESPONSE_SAVE_ERROR_MESSAGE') })) finally: pass attach = Attachment() return make_response( jsonify({ "code": app.config.get('RESPONSE_SAVE_SUCCESS'), "message": app.config.get('RESPONSE_SAVE_SUCCESS_MESSAGE'), "url": visit_path, "type": file_type, "title": file_name, "size": attach_size, "original": file_name, "state": "SUCCESS" }))