def checkin_checkout(doc_id): doc = get_document(doc_id) action = request.form.get("action") if action not in ("checkout", "lock", "unlock"): raise BadRequest("Unknown action: %r" % action) session = sa.orm.object_session(doc) if action in ("lock", "checkout"): doc.lock = current_user d = doc.updated_at # prevent change of last modification date doc.updated_at = datetime.utcnow() session.flush() doc.updated_at = d session.commit() if action == "lock": return redirect(url_for(doc)) elif action == "checkout": return document_download(doc_id, attach=True) if action == "unlock": del doc.lock d = doc.updated_at # prevent change of last modification date doc.updated_at = datetime.utcnow() session.flush() doc.updated_at = d session.commit() return redirect(url_for(doc))
def render_line(self, entity): line = [] for col in self.columns: if type(col) == str: column_name = col else: column_name = col['name'] value = entity.display_value(column_name) # Manual massage. if value is None: value = "" elif 'display_fmt' in col: value = col['display_fmt'](value) if column_name == 'name': cell = Markup('<a href="%s">%s</a>' % (url_for(entity), cgi.escape(value))) elif isinstance(value, Entity): cell = Markup('<a href="%s">%s</a>' % (url_for(value), cgi.escape(value.name))) elif isinstance(value, basestring)\ and (value.startswith("http://") or value.startswith("www.")): cell = Markup(linkify_url(value)) elif col.get('linkable'): cell = Markup('<a href="%s">%s</a>' % (url_for(entity), cgi.escape(unicode(value)))) else: cell = unicode(value) line.append(cell) return line
def document_send(doc_id): doc = get_document(doc_id) recipient = request.form.get("recipient") user_msg = request.form.get("message") site_name = "[{}] ".format(current_app.config["SITE_NAME"]) sender_name = current_user.name subject = site_name + _("{sender} sent you a file").format( sender=sender_name) msg = Message(subject) msg.sender = current_user.email msg.recipients = [recipient] msg.body = render_template_i18n( "documents/mail_file_sent.txt", sender_name=sender_name, message=user_msg, document_url=url_for(doc), filename=doc.title, ) filename = doc.title msg.attach(filename, doc.content_type, doc.content) mail.send(msg) flash(_("Email successfully sent"), "success") return redirect(url_for(doc))
def document_send(doc_id): doc = get_document(doc_id) recipient = request.form.get("recipient") user_msg = request.form.get("message") site_name = "[{}] ".format(current_app.config["SITE_NAME"]) sender_name = current_user.name subject = site_name + _("{sender} sent you a file").format(sender=sender_name) msg = Message(subject) msg.sender = current_user.email msg.recipients = [recipient] msg.body = render_template_i18n( "documents/mail_file_sent.txt", sender_name=sender_name, message=user_msg, document_url=url_for(doc), filename=doc.title, ) filename = doc.title msg.attach(filename, doc.content_type, doc.content) mail.send(msg) flash(_("Email successfully sent"), "success") return redirect(url_for(doc))
def url_value_preprocess(self, endpoint, view_args): model_name = view_args.pop("Model", None) group = view_args.pop("group", _MARKER) if group == "_": # "General" group group = "" if group is not _MARKER: view_args["group"] = group if model_name is not None: svc = get_service("vocabularies") Model = svc.get_vocabulary(name=model_name, group=group) g.breadcrumb.append( BreadcrumbItem( label=Model.Meta.group if group else _("Global"), url=url_for(".vocabularies_group", group=group or "_"), )) g.breadcrumb.append( BreadcrumbItem( label=Model.Meta.label, url=url_for(".vocabularies_model", group=group or "_", Model=Model.Meta.name), )) view_args["Model"] = Model
def url_value_preprocess(self, endpoint, view_args): Model = view_args.pop('Model', None) group = view_args.pop('group', _MARKER) if group == u'_': # "General" group group = None if group is not _MARKER: view_args['group'] = group if Model is not None: svc = self.svc Model = svc.get_vocabulary(name=Model, group=group) g.breadcrumb.append( BreadcrumbItem( label=Model.Meta.group if group else _('Global'), url=url_for('.vocabularies_group', group=group or u'_'), )) g.breadcrumb.append( BreadcrumbItem( label=Model.Meta.label, url=url_for('.vocabularies_model', group=group or u'_', Model=Model.Meta.name), )) view_args['Model'] = Model
def url_value_preprocess(self, endpoint, view_args): Model = view_args.pop('Model', None) group = view_args.pop('group', _MARKER) if group == u'_': # "General" group group = None if group is not _MARKER: view_args['group'] = group if Model is not None: svc = self.svc Model = svc.get_vocabulary(name=Model, group=group) g.breadcrumb.append(BreadcrumbItem( label=Model.Meta.group if group else _('Global'), url=url_for('.vocabularies_group', group=group or u'_'), )) g.breadcrumb.append(BreadcrumbItem( label=Model.Meta.label, url=url_for('.vocabularies_model', group=group or u'_', Model=Model.Meta.name), )) view_args['Model'] = Model
def checkin_checkout(doc_id): doc = get_document(doc_id) action = request.form.get('action') if action not in (u'checkout', u'lock', u'unlock'): raise BadRequest(u'Unknown action: %r' % action) session = sa.orm.object_session(doc) if action in (u'lock', u'checkout'): doc.lock = current_user d = doc.updated_at # prevent change of last modification date doc.updated_at = datetime.utcnow() session.flush() doc.updated_at = d session.commit() if action == u'lock': return redirect(url_for(doc)) elif action == u'checkout': return document_download(doc_id, attach=True) if action == u'unlock': del doc.lock d = doc.updated_at # prevent change of last modification date doc.updated_at = datetime.utcnow() session.flush() doc.updated_at = d session.commit() return redirect(url_for(doc))
def send_post_to_user(community, post, member): recipient = member.email subject = f"[{community.name}] {post.title}" config = current_app.config SENDER = config.get("BULK_MAIL_SENDER", config["MAIL_SENDER"]) SBE_FORUM_REPLY_BY_MAIL = config.get("SBE_FORUM_REPLY_BY_MAIL", False) SBE_FORUM_REPLY_ADDRESS = config.get("SBE_FORUM_REPLY_ADDRESS", SENDER) SERVER_NAME = config.get("SERVER_NAME", "example.com") list_id = '"{} forum" <forum.{}.{}>'.format( community.name, community.slug, SERVER_NAME ) forum_url = url_for("forum.index", community_id=community.slug, _external=True) forum_archive_url = url_for( "forum.archives", community_id=community.slug, _external=True ) extra_headers = { "List-Id": list_id, "List-Archive": f"<{forum_archive_url}>", "List-Post": f"<{forum_url}>", "X-Auto-Response-Suppress": "All", "Auto-Submitted": "auto-generated", } if SBE_FORUM_REPLY_BY_MAIL: name = SBE_FORUM_REPLY_ADDRESS.rsplit("@", 1)[0] domain = SBE_FORUM_REPLY_ADDRESS.rsplit("@", 1)[1] replyto = build_reply_email_address(name, post, member, domain) msg = Message( subject, sender=SBE_FORUM_REPLY_ADDRESS, recipients=[recipient], reply_to=replyto, extra_headers=extra_headers, ) else: msg = Message( subject, sender=SENDER, recipients=[recipient], extra_headers=extra_headers ) ctx = { "community": community, "post": post, "member": member, "MAIL_REPLY_MARKER": MAIL_REPLY_MARKER, "SBE_FORUM_REPLY_BY_MAIL": SBE_FORUM_REPLY_BY_MAIL, } msg.body = render_template_i18n("forum/mail/new_message.txt", **ctx) msg.html = render_template_i18n("forum/mail/new_message.html", **ctx) logger.debug("Sending new post by email to %r", member.email) try: mail.send(msg) except BaseException: # log to sentry if enabled logger.error("Send mail to user failed", exc_info=True)
def send_post_to_user(community, post, member): recipient = member.email subject = "[{}] {}".format(community.name, post.title) config = current_app.config sender = config.get("BULK_MAIL_SENDER", config["MAIL_SENDER"]) SBE_FORUM_REPLY_BY_MAIL = config.get("SBE_FORUM_REPLY_BY_MAIL", False) SERVER_NAME = config.get("SERVER_NAME", "example.com") list_id = '"{} forum" <forum.{}.{}>'.format(community.name, community.slug, SERVER_NAME) forum_url = url_for("forum.index", community_id=community.slug, _external=True) forum_archive = url_for("forum.archives", community_id=community.slug, _external=True) extra_headers = { "List-Id": list_id, "List-Archive": "<{}>".format(forum_archive), "List-Post": "<{}>".format(forum_url), "X-Auto-Response-Suppress": "All", "Auto-Submitted": "auto-generated", } if SBE_FORUM_REPLY_BY_MAIL and config["MAIL_ADDRESS_TAG_CHAR"] is not None: name = sender.rsplit("@", 1)[0] domain = sender.rsplit("@", 1)[1] replyto = build_reply_email_address(name, post, member, domain) msg = Message( subject, sender=sender, recipients=[recipient], reply_to=replyto, extra_headers=extra_headers, ) else: msg = Message(subject, sender=sender, recipients=[recipient], extra_headers=extra_headers) ctx = { "community": community, "post": post, "member": member, "MAIL_REPLY_MARKER": MAIL_REPLY_MARKER, "SBE_FORUM_REPLY_BY_MAIL": SBE_FORUM_REPLY_BY_MAIL, } msg.body = render_template_i18n("forum/mail/new_message.txt", **ctx) msg.html = render_template_i18n("forum/mail/new_message.html", **ctx) logger.debug("Sending new post by email to %r", member.email) try: mail.send(msg) except BaseException: logger.error("Send mail to user failed", exc_info=True) # log to sentry if enabled
def make_tabs(user): return [ dict(id='profile', label=_(u'Profile'), link=url_for(user, tab='profile')), # dict(id='conversations', label=_(u'Conversations'), link=url_for(user), is_online=True), dict(id='documents', label=_(u'Documents'), link=url_for(user, tab='documents')), dict(id='images', label=_(u'Images'), link=url_for(user, tab='images')), dict(id='audit', label=_(u'Audit'), link=url_for(user, tab='audit')), ]
def document_preview(doc_id): doc = get_document(doc_id) if not doc.antivirus_ok: return "Waiting for antivirus to finish" if doc.content_type == "application/pdf": return redirect( url_for(".document_view_pdf", community_id=g.community.slug, doc_id=doc.id) ) else: return redirect( url_for(".document_download", community_id=g.community.slug, doc_id=doc.id) )
def folder_post(folder_id): """A POST on a folder can result on several different actions (depending on the `action` parameter).""" folder = get_folder(folder_id) action = request.form.get("action") if action == "edit": return folder_edit(folder) elif action == "upload": return upload_new(folder) elif action == "download": return download_multiple(folder) elif action == "delete": return delete_multiple(folder) elif action == "new": return create_subfolder(folder) elif action == "move": return move_multiple(folder) elif action == "change-owner": return change_owner(folder) else: # Probably an error or a hack attempt. # Logger will inform sentry if enabled logger = logging.getLogger(__name__) logger.error("Unknown folder action.", extra={"stack": True}) flash(_("Unknown action."), "error") return redirect(url_for(folder))
def get_attachments_from_dms(community): index_service = get_service("indexing") filters = wq.And( [ wq.Term("community_id", community.id), wq.Term("object_type", Document.entity_type), ] ) sortedby = whoosh.sorting.FieldFacet("created_at", reverse=True) documents = index_service.search("", filter=filters, sortedby=sortedby, limit=50) attachments = [] for doc in documents: url = url_for(doc) attachment = Attachment( url, doc["name"], doc["owner_name"], doc["created_at"], doc.get("content_length"), doc.get("content_type", ""), ) attachments.append(attachment) return attachments
def get_all_rules(app): rules = sorted(app.url_map.iter_rules(), key=lambda x: x.endpoint) for rule in rules: if "GET" not in rule.methods: continue if rule.arguments: continue endpoint = rule.endpoint print(endpoint) # Skip several exceptions. if endpoint in ENDPOINTS_TO_SKIP: continue if any(re.match(p, endpoint) for p in PATTERNS_TO_SKIP): continue url = url_for(endpoint) if "/ajax/" in url: continue yield rule
def test_all_simple_endpoints_as_admin(client, app, db, request_ctx): # FIXME: not done yet warnings.simplefilter("ignore") # app.services['security'].start() login_as_admin(client, db) errors = [] for rule in all_rules_to_test(app): endpoint = rule.endpoint if endpoint in ENDPOINTS_TO_IGNORE: continue if endpoint.endswith(".list_json2") or endpoint.endswith(".export_xls"): continue url = url_for(endpoint) try: r = client.get(url) except BaseException: errors.append((endpoint, "500", rule.rule)) continue errors.append((endpoint, str(r.status_code), rule.rule)) if r.status_code != 200: print(endpoint, r.status_code, rule.rule) # assert r.status_code == 200, "for endpoint = '{}'".format(rule.endpoint) print(78 * "-") for t in errors: print(" ".join(t)) print()
def _do_register_js_api(sender: Application) -> None: app = sender # pyre-fixme[6]: Expected `str` for 2nd param but got `Dict[_KT, _VT]`. js_api = app.js_api.setdefault("search", {}) # hack to avoid url_for escape '%' # pyre-fixme[16]: `str` has no attribute `__setitem__`. js_api["live"] = url_for("search.live", q="") + "%QUERY"
def voc_edit_url(self, item): return url_for( "." + self.id + "_edit", group=item.Meta.group or "_", Model=item.Meta.name, object_id=item.id, )
def voc_edit_url(self, item): return url_for( '.' + self.id + '_edit', group=item.Meta.group or '_', Model=item.Meta.name, object_id=item.id, )
def excel_export_actions(self): actions = [] for column_set in self.EXCEL_EXPORT_RELATED: url = url_for(".export_to_xls", related=column_set.related_attr) actions.append((url, column_set.export_label)) return actions
def document_preview(doc_id): doc = get_document(doc_id) if not doc.antivirus_ok: return "Waiting for antivirus to finish" if doc.content_type == "application/pdf": return redirect( url_for(".document_view_pdf", community_id=g.community.slug, doc_id=doc.id)) else: return redirect( url_for(".document_download", community_id=g.community.slug, doc_id=doc.id))
def data(self, *args, **kwargs): task_id = request.args.get("task_id") task = celery.result.AsyncResult(task_id) result = dict(state=task.state, exported=0, total=0) if task.state in ("REVOKED", "PENDING", "STARTED"): return result if task.state == "PROGRESS": result.update(task.result) return result if task.state == "FAILURE": result["message"] = _("An error happened during generation of file.") return result if task.state == "SUCCESS": result.update(task.result) handle = result["handle"] uploads = current_app.extensions["uploads"] filemeta = uploads.get_metadata(current_user, handle) result["filename"] = filemeta.get("filename", "export.xlsx") result["downloadUrl"] = url_for( "uploads.handle", handle=handle, _external=True ) return result # unattended state, return data anyway # FIXME: log at error level for sentry? return result
def change_view_style(folder_id): folder = get_folder(folder_id) if request.method == "POST": view_style = request.form["view_style"] if view_style == "gallery_view": session["sbe_doc_view_style"] = "gallery_view" else: session["sbe_doc_view_style"] = "thumbnail_view" return redirect( url_for(".folder_view", folder_id=folder_id, community_id=folder.community.slug)) else: return redirect( url_for(".folder_view", folder_id=folder_id, community_id=folder.community.slug))
def post(self, action=None): is_closed = action == "close" self.obj.closed = is_closed sa.orm.object_session(self.obj).commit() msg = self.CLOSED_MSG if is_closed else self.REOPENED_MSG flash(str(msg)) return self.redirect(url_for(self.obj))
def post(self, action=None): is_closed = action == "close" self.obj.closed = is_closed sa.orm.object_session(self.obj).commit() msg = self.CLOSED_MSG if is_closed else self.REOPENED_MSG flash(text_type(msg)) return self.redirect(url_for(self.obj))
def render_view(self, field, **kwargs): objs = field.object_data if not field.multiple: objs = [objs] return u', '.join( u'<a href="{}">{}</a>'.format(url_for(o), cgi.escape(o.name)) for o in objs if o)
def document_view_pdf(doc_id): doc = get_document(doc_id) if not doc.antivirus_ok: return "Waiting for antivirus to finish" return render_template("documents/view_pdf.html", pdf_url=url_for(".document_download", community_id=g.community.slug, doc_id=doc.id))
def get_form_context(self, obj): """ Return a dict: form instance, action button, submit url... Used by macro m_attachment_form(entity) """ ctx = {} ctx['url'] = url_for('attachments.create', entity_id=obj.id) ctx['form'] = self.Form() ctx['buttons'] = [UPLOAD_BUTTON] return ctx
def get_form_context(self, obj): """Return a dict: form instance, action button, submit url... Used by macro m_attachment_form(entity) """ return { 'url': url_for('attachments.create', entity_id=obj.id), 'form': self.Form(), 'buttons': [UPLOAD_BUTTON], }
def get_form_context(self, obj, ns=None): """ Return a dict: form instance, action button, submit url... Used by macro m_tags_form(entity) """ ctx = {} ctx['url'] = url_for('entity_tags.edit', object_id=obj.id) ctx['form'] = self.entity_tags_form(obj)(obj=obj, ns=ns) ctx['buttons'] = [EDIT_BUTTON] return ctx
def get_form_context(self, obj): """Return a dict: form instance, action button, submit url... Used by macro m_attachment_form(entity) """ return { "url": url_for("attachments.create", entity_id=obj.id), "form": self.Form(), "buttons": [UPLOAD_BUTTON], }
def document_delete(doc_id): doc = get_document(doc_id) check_write_access(doc) parent_folder = doc.parent repository.delete_object(doc) db.session.commit() flash(_("File successfully deleted."), "success") return redirect(url_for(parent_folder))
def change_view_style(folder_id): folder = get_folder(folder_id) if request.method == "POST": view_style = request.form["view_style"] if view_style == "gallery_view": session["sbe_doc_view_style"] = "gallery_view" else: session["sbe_doc_view_style"] = "thumbnail_view" return redirect( url_for( ".folder_view", folder_id=folder_id, community_id=folder.community.slug ) ) else: return redirect( url_for( ".folder_view", folder_id=folder_id, community_id=folder.community.slug ) )
def render_line(self, entity): line = [] for col in self.columns: if type(col) == str: column_name = col else: column_name = col['name'] value = entity.display_value(column_name) cell = None has_custom_display = False # Manual massage. # 'display_fun' gets value *and* entity: useful to perform # specific markup based on other entity values. # 'display_fmt' is for simple value formatting (format_date from # babel for example) if value is None: value = "" elif 'display_fun' in col: has_custom_display = True value = col['display_fun'](entity, value) elif 'display_fmt' in col: value = col['display_fmt'](value) if has_custom_display: cell = value elif column_name == 'name': cell = Markup('<a href="%s">%s</a>' % (url_for(entity), cgi.escape(value))) elif isinstance(value, Entity): cell = Markup('<a href="%s">%s</a>' % (url_for(value), cgi.escape(value.name))) elif (isinstance(value, string_types) and (value.startswith("http://") or value.startswith("www."))): cell = Markup(linkify_url(value)) elif col.get('linkable'): cell = Markup('<a href="%s">%s</a>' % (url_for(entity), cgi.escape(unicode(value)))) else: cell = unicode(value) line.append(cell) return line
def create_subfolder(folder): check_write_access(folder) title = request.form.get("title", "") description = request.form.get("description", "") subfolder = folder.create_subfolder(title) subfolder.description = description db.session.commit() return redirect(url_for(folder))
def get_form_context(self, obj, ns=None): """Return a dict: form instance, action button, submit url... Used by macro m_tags_form(entity) """ return { "url": url_for("entity_tags.edit", object_id=obj.id), "form": self.entity_tags_form(obj)(obj=obj, ns=ns), "buttons": [EDIT_BUTTON], }
def get_form_context(self, obj): """Return a dict: form instance, action button, submit url... Used by macro m_comment_form(entity) """ return { "url": url_for("comments.create", entity_id=obj.id), "form": CommentForm(), "buttons": [COMMENT_BUTTON], }
def get_form_context(self, obj): """Return a dict: form instance, action button, submit url... Used by macro m_comment_form(entity) """ ctx = {} ctx['url'] = url_for('comments.create', entity_id=obj.id) ctx['form'] = CommentForm() ctx['buttons'] = [COMMENT_BUTTON] return ctx
def document_edit(doc_id, folder_id=None): doc = get_document(doc_id) if folder_id: folder = get_folder(folder_id) else: folder = None check_write_access(doc) changed = edit_object(doc) if changed: db.session.commit() flash(_("Document properties successfully edited."), "success") else: flash(_("You didn't change any property."), "success") if folder: return redirect(url_for(folder)) else: return redirect(url_for(doc))
def folder_edit(folder): check_write_access(folder) changed = edit_object(folder) if changed: db.session.commit() flash(_("Folder properties successfully edited."), "success") else: flash(_("You didn't change any property."), "success") return redirect(url_for(folder))
def breadcrumbs_for(object): if object is None: return [] bc = [{"label": object.title}] parent = object.parent while parent and not parent.is_root_folder: bc = [{"label": parent.title, "path": url_for(parent)}] + bc parent = parent.parent return bc
def breadcrumbs_for(object): if object is None: return [] bc = [dict(label=object.title)] parent = object.parent while parent and not parent.is_root_folder: bc = [dict(label=parent.title, path=url_for(parent))] + bc parent = parent.parent return bc
def document_view_pdf(doc_id): doc = get_document(doc_id) if not doc.antivirus_ok: return "Waiting for antivirus to finish" return render_template( "documents/view_pdf.html", pdf_url=url_for( ".document_download", community_id=g.community.slug, doc_id=doc.id ), )
def change_owner(folder): check_manage_access(folder) items = itertools.chain(*get_selected_objects(folder)) user_id = request.form.get("new_owner", type=int) user = User.query.get(user_id) for item in items: item.owner = user db.session.commit() return redirect(url_for(folder))
def document_upload(doc_id): doc = get_document(doc_id) check_write_access(doc) fd = request.files["file"] doc.set_content(fd.read(), fd.content_type) del doc.lock self = unwrap(current_app) activity.send(self, actor=current_user, verb="update", object=doc) db.session.commit() flash(_("New version successfully uploaded"), "success") return redirect(url_for(doc))
def test_admin_panel_reorder(self): Voc = self.DefaultVoc session = self.session items = [ Voc(label=u'First', position=0), Voc(label=u'Second', position=2), Voc(label=u'Third', position=3) ] for i in items: session.add(i) session.commit() first, second, third = items url = url_for('admin.vocabularies') base_data = {'Model': Voc.Meta.name} data = {'down': first.id} data.update(base_data) r = self.client.post(url, data=data) assert r.status_code == 302 assert r.headers['Location'] == u'http://localhost/admin/vocabularies' assert Voc.query.order_by(Voc.position).all() == [second, first, third] data = {'up': first.id, 'return_to': 'group'} data.update(base_data) r = self.client.post(url, data=data) assert r.status_code == 302 assert r.headers['Location'] == u'http://localhost/admin/vocabularies/_/' assert Voc.query.order_by(Voc.position).all() == [first, second, third] data = {'up': first.id, 'return_to': 'model'} data.update(base_data) r = self.client.post(url, data=data) assert r.status_code == 302 assert (r.headers['Location'] == u'http://localhost/admin/vocabularies/_/defaultstates/') assert Voc.query.order_by(Voc.position).all() == [first, second, third] data = {'down': third.id} data.update(base_data) r = self.client.post(url, data=data) assert r.status_code == 302 assert r.headers['Location'] == u'http://localhost/admin/vocabularies' assert Voc.query.order_by(Voc.position).all() == [first, second, third] data = {'up': third.id} data.update(base_data) r = self.client.post(url, data=data) assert r.status_code == 302 assert r.headers['Location'] == u'http://localhost/admin/vocabularies' assert Voc.query.order_by(Voc.position).all() == [first, third, second]
def test_admin_panel_reorder(app, db, session, client, test_request_context): db.create_all() items = [ Voc(label="First", position=0), Voc(label="Second", position=2), Voc(label="Third", position=3), ] for i in items: session.add(i) session.commit() first, second, third = items url = url_for("admin.vocabularies") base_data = {"Model": Voc.Meta.name} data = {"down": first.id} data.update(base_data) r = client.post(url, data=data) assert r.status_code == 302 assert path_from_url(r.location) == "/admin/vocabularies" assert Voc.query.order_by(Voc.position).all() == [second, first, third] data = {"up": first.id, "return_to": "group"} data.update(base_data) r = client.post(url, data=data) assert r.status_code == 302 assert path_from_url(r.location) == "/admin/vocabularies/_/" assert Voc.query.order_by(Voc.position).all() == [first, second, third] data = {"up": first.id, "return_to": "model"} data.update(base_data) r = client.post(url, data=data) assert r.status_code == 302 assert path_from_url(r.location) == "/admin/vocabularies/_/defaultstates/" assert Voc.query.order_by(Voc.position).all() == [first, second, third] data = {"down": third.id} data.update(base_data) r = client.post(url, data=data) assert r.status_code == 302 assert path_from_url(r.location) == "/admin/vocabularies" assert Voc.query.order_by(Voc.position).all() == [first, second, third] data = {"up": third.id} data.update(base_data) r = client.post(url, data=data) assert r.status_code == 302 assert path_from_url(r.location) == "/admin/vocabularies" assert Voc.query.order_by(Voc.position).all() == [first, third, second]
def render_line(self, entity): line = [] make_link_on = self.options.get("make_link_on") for col in self.columns: if type(col) == str: column_name = col else: column_name = col['name'] value = entity for attr in column_name.split('.'): value = value.display_value(attr) # Manual massage. if value is None: value = "" if column_name == make_link_on or column_name == 'name' or \ col.get('linkable'): cell = Markup('<a href="%s">%s</a>' % (url_for(entity), cgi.escape(unicode(value)))) elif isinstance(value, Entity): cell = Markup('<a href="%s">%s</a>' % (url_for(value), cgi.escape(value.name))) elif isinstance(value, basestring) \ and (value.startswith("http://") or value.startswith("www.")): cell = Markup(linkify_url(value)) elif value in (True, False): cell = u'\u2713' if value else u'' # Unicode "Check mark" elif isinstance(value, list): cell = "; ".join(value) else: cell = unicode(value) line.append(cell) return line
def refresh_preview(doc_id): """Force to compute a new preview.""" doc = get_document(doc_id) if not doc: raise NotFound() ct = doc.find_content_type(doc.content_type) if ct != doc.content_type: doc.content_type = ct db.session.commit() check_manage_access(doc) convert_document_content.apply([doc_id]) preview_document.apply([doc_id]) return redirect(url_for(doc))