def load_img1(filename): keys = requests.put(backendurl + filename) keys = keys.json() url = None for key in keys.keys(): if "slice" in key: url = keys[key]['url'] dimg = get_template_attribute("base.html", "geturl1") keys = requests.get(backendurl + filename) keys = keys.json() url2 = None file2 = None for key in keys.keys(): if "sliceog" in key: url2 = keys[key]['url'] elif "mask" in key: file2 = key dimg = get_template_attribute("base.html", "geturl2") dimg(url2) fin = niifiles.get_blob(keys[file2]['name']) fin.download_to_filename(app.config["UPLOAD_FOLDER"] + keys[file2]['name']) #return send_from_directory(directory = app.config["UPLOAD_FOLDER"], filename=keys[file2]['name']) os.remove(app.config["UPLOAD_FOLDER"] + keys[file2]['name']) keyfil = requests.delete(backendurl + filename) return render_template("base.html", urlslice = url, urlslice1 = url2)#, send_from_directory(directory = app.config["UPLOAD_FOLDER"], filename=keys[file2]['name'])
def get_next_move(): grid_macro = get_template_attribute('components.html', 'grid_pattern') board_template = grid_macro(board_grid, 'board') move = solver.get_next_move() if type(move) == str: return { 'state': move, 'board': board_template } # TODO: macro doesn't take some keys move_macro = get_template_attribute('components.html', 'move') move_template = move_macro(**(move.__dict__)) moves.append(move) the_hole = [hole for hole in solver.all_holes if hole['id'] == move.global_hole_id][0] add_piece_edges_to_grid(board_grid, puzzle.get_piece(move.piece, move.orient), move.coord, the_hole['offset']) return { 'message': move_template, 'solved': solver.state.solved, 'board': board_template }
def _add_comment(): """ajax add comment HTML """ per_page = current_app.config['FLASKY_ANSWERS_PER_PAGE'] id = request.args.get('answer_id') answer = Answer.query.get_or_404(id) comment = request.args.get('comment') answers = Answer.query.get_or_404(id) page = 1 result = False if current_user.can(Permission.COMMENT): comment = Comment(body=comment, author=current_user._get_current_object(), answer_id=id) db.session.add(comment) db.session.commit() page = (answer.comments.count() - 1) / per_page + 1 result = True pagination = Comment.query.order_by( Comment.timestamp).filter_by(answer_id=id).paginate(page, per_page=per_page, error_out=False) macro_comment = get_template_attribute("_comments.html", "render_comments") macro_page = get_template_attribute("_page.html", "render_page") comments = pagination.items return jsonify({ 'result': result, 'comment_html': macro_comment(comments), 'page_html': macro_page(pagination), 'comments_timestamp': [comment.timestamp for comment in comments], 'comments_id': [comment.id for comment in comments] })
def submit_post(obj_response, files, form_values): form = forms.PostForm(**form_values) if form.validate(): parent_id = None if form.parent_id.data: parent_id = form.parent_id.data post = Post.submit(form.content.data, current_user, parent_id) if parent_id: render_comment = get_template_attribute('macros.html', 'render_comment') obj_response.html_prepend( ''.join(['#post-', parent_id, '-comments']), render_comment(post, current_user).unescape()) # update parent comments counter obj_response.script(''.join([ '$("#load_comment_button_', parent_id, '").children(".badge").html(', str(Post.query.filter_by(parent_id=parent_id).count()), ')' ])) else: render_post = get_template_attribute('macros.html', 'render_post') obj_response.html_prepend( '#post-container', render_post(post, current_user).unescape()) obj_response.script("$('#collapsable_post_form').collapse('hide');") form.reset() render_post_form = get_template_attribute('macros.html', 'render_post_form') obj_response.html('#collapsable_post_form', render_post_form(form, current_user).unescape()) # register again the sijax upload plugin obj_response.script( 'sjxUpload.registerForm({"callback": "post_form_upload", "formId": "post_form"});' )
def load_more_laws(obj_response, group_name, status_name, order, last): laws = Law.get_more(group_name=group_name, status_name=status_name, order=order, last=last) render_law = get_template_attribute('macros.html', 'render_law') more_laws_panel = get_template_attribute('macros.html', 'more_laws_panel') if laws: for law in laws: obj_response.html_append( '#laws-container', render_law(law, current_user, actions_footer=True).unescape()) if order == 'id': panel = more_laws_panel(group_name, status_name, order, laws[-1].id).unescape() elif order == 'date': panel = more_laws_panel(group_name, status_name, order, laws[-1].date).unescape() else: return obj_response.html('#load_more_container', panel) # refresh masonry to load the new laws correctly obj_response.script('$(".masonry-grid").masonry( "reloadItems" )') obj_response.script('$(".masonry-grid").masonry()') # refresh and re-enable waypoint to achieve continuous loading obj_response.script('Waypoint.refreshAll()') obj_response.script('Waypoint.enableAll()') else: obj_response.html('#load_more_container', more_laws_panel().unescape())
def _add_comment(): """ajax add comment HTML """ per_page = current_app.config['FLASKY_ANSWERS_PER_PAGE'] id = request.args.get('answer_id') answer = Answer.query.get_or_404(id) comment =request.args.get('comment') answers = Answer.query.get_or_404(id) page = 1 result= False if current_user.can(Permission.COMMENT): comment = Comment(body=comment, author=current_user._get_current_object(), answer_id=id) db.session.add(comment) db.session.commit() page = (answer.comments.count()-1)/per_page + 1 result=True pagination = Comment.query.order_by(Comment.timestamp).filter_by(answer_id=id).paginate( page,per_page=per_page,error_out=False ) macro_comment = get_template_attribute("_comments.html", "render_comments") macro_page = get_template_attribute("_page.html", "render_page") comments = pagination.items return jsonify({'result': result, 'comment_html': macro_comment(comments), 'page_html': macro_page(pagination), 'comments_timestamp': [comment.timestamp for comment in comments], 'comments_id': [comment.id for comment in comments] })
def get_news() -> List[Dict[str, Any]]: """Gets the context for the newslist from the article files in `news/` Returns: List[Dict[str, any]]: One Dict per news article with keys and values: `title` (str): article title (plain text) `lede` (str): article lede (HTML) `date` (datetime.date): date of initial publication `article_name`: filename of the article file (Jinja or Markdown) with the extension removed. """ news = [] for filename in os.listdir(os.path.join(ROOT_DIR, "templates", "content", "news")): if filename.endswith(".md"): template_name = os.path.join( "content", "news", removesuffix(filename, ".md") + ".html.jinja2" ) else: template_name = os.path.join("content", "news", filename) title = get_template_attribute(template_name, "title") lede = get_template_attribute(template_name, "lede") published = date.fromisoformat(filename[:10]) news.append( { "title": title.strip(), "lede": lede.strip(), "date": published, "article_name": removesuffix(removesuffix(filename, ".md"), ".html.jinja2"), } ) if len(lede) == 0: print("No lede found for", filename) news.sort(key=itemgetter("date"), reverse=True) return news
def search(type=False): is_ajax = request.args.get('ajax', None) query = request.args.get('query', "") page = int(request.args.get('page', "1")) if not type: return render_template('frontend/search.html', query=query, title='Search for') if is_ajax and query == "": return 'I am not searching for anything' num = 10 start = (page - 1) * num if type == 'things': results = elastic.search( 'thing', query={ 'title^3,short_description,description,makers_string': query }, start=start, num=num) content = get_template_attribute('frontend/macros.html', 'search_results')(results, 'thing.detail') elif type == 'makers': results = elastic.search('maker', query={'title^3,searchable_text': query}, start=start, num=num) content = get_template_attribute('frontend/macros.html', 'search_results')(results, 'maker.detail') elif type == 'discussions': results = [] content = get_template_attribute('frontend/macros.html', 'search_results')(results, 'talk.thread') elif type == 'collections': results = elastic.search( 'collection', query={ 'title^3,short_description^2,description,searchable_text': query }, start=start, num=num) content = get_template_attribute('frontend/macros.html', 'search_results')(results, 'collection.detail') if is_ajax: return content else: return render_template('frontend/search_results.html', query=query, title='Search for', content=content, page_next=page + 1, type=type)
def load_piece(): piece = Piece.query.order_by(db.func.random()).first() piece_macro = get_template_attribute('macros/_piece.html', 'render_piece_in_index_page') piece_creator_macro = get_template_attribute('macros/_piece.html', 'render_piece_creator_info') return { 'result': True, 'piece_html': piece_macro(piece), 'piece_creator_html': piece_creator_macro(piece) }
def fetch_tile_settings(): dashboard_id = request.get_json()['dashboard_id'] tile_id = request.get_json()['tile_id'] check_access(lambda: auth.access_dashboard(dashboard_id)) tile = tiles.Tile.select(dashboard_id, tile_id) if not tile: return error(message='No tile found, please refresh the page') check_access(lambda: auth.access_report_instances(tile.report_id)) res = {} res['report_id'] = tile.report_id latest_instance_id = tile.report.fetch_latest_instance_id(tile.tile_options['tags']) if not latest_instance_id: return error(message='No report instances for report %s - at least one report instance is needed to display tile settings.' % tile.report.report_name) ri = tile.report.fetch_single_instance(latest_instance_id, tile.tile_options['tags']) res['latest_instance_id'] = latest_instance_id res['html_newest_table'] = get_template_attribute('m.html', 'table_as_html_table')(ri.table) if tile.tile_options['tags']: res['html_selected_tags'] = get_template_attribute('m.html', 'selected_tags')(tile.tile_options['tags']) tpcreator_uispec = tile.tile_options.get('tpcreator_uispec') if not tpcreator_uispec: tpcreator_uispec = tpcreator.suggested_tpcreator_uispec(tile.tile_options['tags']) res['html_tpcreator_content'] = get_template_attribute('m.html', 'tpcreator_content')(tpcreator_uispec) else: res['html_selected_tags'] = None res['html_tpcreator_content'] = None res['tile_options'] = tile.tile_options res['report_name'] = tile.report.report_name html_series_specs = [] for series_spec in tile.series_specs(): data_d = {} cell = series_spec.get_cell(ri) if cell: data_d['sampled-from'] = {'rowno': cell.rowno, 'colno': cell.colno} html_series_specs.append(get_template_attribute('m.html', 'series_spec')(series_spec, ri, data_d)) res['html_all_series_specs'] = '\n'.join(html_series_specs) if tile.tile_options.get('sscs'): res['html_sscs'] = get_template_attribute('m.html', 'series_spec_creator_spec')(tile.tile_options['sscs'], ri) else: res['html_sscs'] = None return success(result=res)
def process_cobbler_object(objects, item_name): if objects not in ["distros", "profiles", "systems", "kickstarts"]: return predefined = cobbler_default_data[objects] url_prefix = "/cm/v1/cobbler" url = "{0}/{1}/{2}".format(url_prefix, objects, item_name) method = request.method.lower() template = "" if method == "get": result = request_rest_api(method, url) else: result = request_rest_api(method, url, request.json) if result["result"] and method == "post": result = request_rest_api("get", url) if result["result"] and method in ["get", "post"]: append_select_data(objects, result) if predefined["flag_collection"]: accordion_panel = get_template_attribute( "mesh/cobbler/cobbler_macro.html", "CM_ACCORDION_PANEL_COLLECTION") result["template"] = accordion_panel( objects, result["data"][0]["data"], predefined["field_filter"]["normal"], predefined["button"]["normal"], predefined["field_filter"]) else: accordion_panel = get_template_attribute( "mesh/cobbler/cobbler_macro.html", "CM_ACCORDION_PANEL") result["template"] = accordion_panel( objects, result["data"][0]["data"], predefined["field_filter"]["normal"], predefined["button"]["normal"]) if method == "post": if predefined["flag_collection"]: accordion_panel_add = get_template_attribute( "mesh/cobbler/cobbler_macro.html", "CM_ACCORDION_PANEL_COLLECTION") add_data = get_add_data_dict(objects, result) add_template = accordion_panel_add(objects, add_data["data"], add_data["filter"], add_data["button"], predefined["field_filter"], True) else: accordion_panel_add = get_template_attribute( "mesh/cobbler/cobbler_macro.html", "CM_ACCORDION_PANEL") add_data = get_add_data_dict(objects, result) add_template = accordion_panel_add(objects, add_data["data"], add_data["filter"], add_data["button"], True) result["template"] += add_template return Response(json.dumps(result), status=200, mimetype="application/json")
def search(type=False): is_ajax = request.args.get('ajax', None) query = request.args.get('query', "") page = int(request.args.get('page', "1")) if not type: return render_template( 'frontend/search.html', query=query, title='Search for' ) if is_ajax and query == "": return 'I am not searching for anything' num = 10 start = (page - 1) * num if type == 'things': results = elastic.search('thing', query={ 'title^3,short_description,description,makers_string': query}, start=start, num=num) content = get_template_attribute( 'frontend/macros.html', 'search_results')(results, 'thing.detail') elif type == 'makers': results = elastic.search('maker', query={'title^3,searchable_text': query}, start=start, num=num) content = get_template_attribute( 'frontend/macros.html', 'search_results')(results, 'maker.detail') elif type == 'discussions': results = [] content = get_template_attribute( 'frontend/macros.html', 'search_results')(results, 'talk.thread') elif type == 'collections': results = elastic.search('collection', query={ 'title^3,short_description^2,description,searchable_text': query}, start=start, num=num) content = get_template_attribute( 'frontend/macros.html', 'search_results')(results, 'collection.detail') if is_ajax: return content else: return render_template( 'frontend/search_results.html', query=query, title='Search for', content=content, page_next=page + 1, type=type )
def comment(uid): """评论""" piece = Piece.query.get_or_404(uid) content = request.form.get('comment') root_comment_id = request.form.get('root_comment_id', type=int) target_user_id = request.form.get('target_user_id', type=int) if not content: abort(500) comment = PieceComment(content=content.strip(), piece_id=uid, user_id=g.user.id) if root_comment_id: # 若该评论为sub comment root_comment = PieceComment.query.get_or_404(root_comment_id) target_user = User.query.get_or_404(target_user_id) comment.root_comment_id = root_comment_id comment.target_user_id = target_user_id db.session.add(comment) db.session.commit() if root_comment_id: noti_receiver_id = target_user_id noti_kind = NOTIFICATION_KIND.COMMENT_PIECE_COMMENT else: noti_receiver_id = piece.user_id noti_kind = NOTIFICATION_KIND.COMMENT_PIECE # 推送通知 if noti_receiver_id != g.user.id: noti = Notification(sender_id=g.user.id, target=piece.content, content=content, receiver_id=noti_receiver_id, kind=noti_kind, link="%s#comment_%d" % (url_for('piece.view', uid=uid), comment.id)) db.session.add(noti) db.session.commit() # 返回comment HTML comment_macro = get_template_attribute('macros/_piece.html', 'render_piece_comment') sub_comments_macro = get_template_attribute('macros/_piece.html', 'render_piece_sub_comments') comment_html = comment_macro(comment) # 若为root comment,则在返回的HTML中加入sub_comments if not root_comment_id: comment_html += sub_comments_macro(comment) return comment_html
def send_message(address, macro_name, **kwargs): # get message body body = get_template_attribute('email_messages.html', macro_name)(**kwargs) # try to get message subject try: subject = get_template_attribute('email_messages.html', macro_name+"_subject")(**kwargs) except AttributeError: subject = "Notification" # send mail mail.send_mail(sender="HashBounty <*****@*****.**>", to=address, subject=subject, body=body)
def show_server(server): # get list of graphs for 'server' if server != 'None': lmv2 = Loadmonitorv2(conf) server_params = lmv2.server_params(server)[0] graph_list = lmv2.gen_page(server_params) xivo_server_list = lmv2.xivo_server_list() server_list = {} start_test_date_format = 'No test running' for servername in xivo_server_list: pid = lmv2.is_test_running(servername[0]) if pid is not None: server_list.update({servername[0]: 'true'}) if servername[0] == server: start_test_date = lmv2.start_test_date(servername[0]) start_test_date_format = '{} {} - {}:{}'.format( start_test_date.day, calendar.month_name[start_test_date.month], start_test_date.hour, start_test_date.minute, ) else: server_list.update({servername[0]: 'false'}) else: graph_list = [] xivo_server_list = [] leftmenu_macro = get_template_attribute('_leftmenu.html', 'left_menu') return render_template( 'graphs.html', leftmenu_macro=leftmenu_macro(server_list, server), graphs=graph_list, server=server, start_test_date=start_test_date_format, )
def unfollow(type, id): """ Removes current user as follower Returns JSON """ if type == 'collection': model = Collection.objects.get_or_404(id=id) elif type == 'queue': model = Queue.objects.get_or_404(id=id) elif type == 'maker': model = Maker.objects.get_or_404(id=id) elif type == 'thread': model = Thread.objects.get_or_404(id=id) elif type == 'thing': model = Thing.objects.get_or_404(id=id) else: abort(404) user = User.objects(id=current_user.get_id()).first() model.remove_follower(user) if type == 'collection': cached = Cache.objects(name="collections-for-%s" % current_user.get_id()).first() if cached: cached.delete() return jsonify({ 'result': 'success', 'message': unicode( get_template_attribute('frontend/macros.html', 'follow')(model)) })
def pieces_by_date(): """获取从指定date开始的指定天数的pieces""" start = request.form.get('start') if start: start_date = datetime.strptime(start, '%Y-%m-%d').date() else: start_date = date.today() - timedelta(days=2) days = request.form.get('days', 2, type=int) html = "" pieces_wap_macro = get_template_attribute('macros/_piece.html', 'render_pieces_by_date') data_count = 0 delta = 1 while data_count < days: target_day = start_date - timedelta(days=delta) pieces_count = Piece.query.filter(db.func.date(Piece.created_at) == target_day).count() if pieces_count: pieces_data = Piece.get_pieces_data_by_day(target_day) html += pieces_wap_macro(pieces_data, show_modal=False) next_start_date = (target_day - timedelta(days=1)).strftime("%Y-%m-%d") data_count += 1 delta += 1 return json.dumps({ 'html': html, 'start': next_start_date })
def pieces_by_date(): """获取从指定date开始的指定天数的pieces""" start = request.form.get('start') if start: start_date = datetime.strptime(start, '%Y-%m-%d').date() else: start_date = date.today() - timedelta(days=2) days = request.form.get('days', 2, type=int) html = "" pieces_wap_macro = get_template_attribute('macros/_piece.html', 'render_pieces_by_date') data_count = 0 delta = 1 next_start_date = None while data_count < days and delta < 5: target_day = start_date - timedelta(days=delta) pieces_count = Piece.query.filter( db.func.date(Piece.created_at) == target_day).count() if pieces_count: pieces_data = Piece.get_pieces_data_by_day(target_day) html += pieces_wap_macro(pieces_data, show_modal=False) next_start_date = (target_day - timedelta(days=1)).strftime("%Y-%m-%d") data_count += 1 delta += 1 return json.dumps({'html': html, 'start': next_start_date})
def render(self): render = render_template_string e = self.entry user = render(self._USER_FMT, user=e.user) self.entity_deleted = e.entity is None entity_html = e.entity_name if not self.entity_deleted: try: entity_url = url_for(e.entity) except (BuildError, ValueError): pass else: entity_html = Markup(render( u'<a href="{{ url }}">{{ entity.path or entity.name }}</a>', url=entity_url, entity=e.entity)) if e.type == 0: msg = _(u'{user} created {entity_type} {entity_id} "{entity}"') elif e.related or e.op == 1: msg = _(u'{user} made changes on {entity_type} {entity_id} "{entity}"') elif e.op == 2: msg = _(u'{user} has deleted {entity_type}: {entity_id} "{entity}"') else: raise Exception("Bad entry type: {}".format(e.type)) self.msg = Markup(msg.format(user=user, entity=entity_html, entity_type=e.entity_type.rsplit('.', 1)[-1], entity_id=e.entity_id,)) tmpl = get_template_attribute('admin/_macros.html', 'm_audit_entry') return tmpl(self)
def add_new_tab(): new_tab_name = request.form.get('new_tab_name') new_tab = Tab(name=new_tab_name, user_id=current_user.id, active=False) tabs = Tab.query.filter_by(user_id=current_user.id).all() new_tab.update_order_idx(len(tabs)) db.session.add(new_tab) db.session.commit() tab_html = get_template_attribute('main/macroses.html', 'create_tabs')([new_tab]) tab_content_html = get_template_attribute( 'main/macroses.html', 'create_tasks_area')([[new_tab, []]]) return jsonify({ 'tab_id': new_tab.id, 'tab': tab_html, 'tab_content': tab_content_html })
def validate_snippet(): """Respond to direct /_validate POST requests (AJAX).""" error = None basic_url = request.values.get('basic_url', None) if not basic_url: return render_template('index.html') basic_url = "".join(basic_url.split()) try: validator = validate_repository(basic_url) except HTTPError as e: error = '%d %s' % (e.code, e.msg) except (ValueError, URLError) as e: error = e.args[0] except XMLSyntaxError as e: error = 'Invalid OAI-PMH interface (Identify): %s' % e.args[0] if error is not None: return render_template('index.html', error=error, previous_url=basic_url) admin_email = validator.admin_email repository_name = validator.repository_name results = validator.results categorized_results = categorize_results(results) func = get_template_attribute('_results.html', 'render_results') return func(repository_name, admin_email, categorized_results)
def invite(uid, user_id): """邀请回答""" question = Question.query.get_or_404(uid) user = User.query.get_or_404(user_id) if user_id == g.user.id or user_id == question.user_id: return {'result': False} # 取消邀请 invitation = InviteAnswer.query.filter(InviteAnswer.question_id == uid, InviteAnswer.user_id == user_id, InviteAnswer.inviter_id == g.user.id).first() if invitation: feed = ComposeFeed.query.filter(ComposeFeed.invitation_id == invitation.id).first() db.session.delete(feed) db.session.delete(invitation) db.session.commit() return {'result': True, 'invited': False} else: # 邀请 invitation = InviteAnswer(question_id=uid, user_id=user_id, inviter_id=g.user.id) db.session.add(invitation) db.session.commit() # COMPOSE FEED: 邀请回答 ComposeFeed.invite_to_answer(user, question, invitation) db.session.commit() macro = get_template_attribute("macros/_question.html", "invited_user_wap") return {'result': True, 'invited': True, 'username': user.name, 'user_profile_url': user.profile_url, 'html': macro(user)}
def get_overview(): subgraph_id = request.json.get('subgraph_id') if subgraph_id is None: return jsonify(error='Subgraph id cannot be empty.') try: subgraph_id = int(subgraph_id) except ValueError: return jsonify(error='{} id has to be an integer.'.format( current_app.config['FRONTEND_CONFIG']['Subgraph_term'])) db = get_db() subgraph = db.execute('SELECT * FROM subgraph WHERE id = ?', (subgraph_id, )).fetchone() if subgraph is None: return jsonify(error='{} with id {} does not exist.'.format( current_app.config['FRONTEND_CONFIG']['Subgraph_term'], subgraph_id)) if not subgraph['finished']: return jsonify(error='You have no access to {} with id {}.'.format( current_app.config['FRONTEND_CONFIG']['subgraph_term'], subgraph_id)) render_overview_table = get_template_attribute('tool/overview_table.html', 'overview') overview_table = render_overview_table( get_subgraph_knowledge(subgraph_id).get_graph(clean=True, ontology=True)) return jsonify(overview_table=overview_table)
def probe(): url = request.values.get("url") if not url or not is_safe_url(url): abort(400) results = probe_url(url) func = get_template_attribute("_results.html", "render_results") return func(url, results)
def send_template(to, template, data): if not current_app.config.get('SMTP_FROM'): return subj = get_template_attribute(template, 'subject') body = render_template(template, **data) send_mail(current_app.config['SMTP_FROM'], to, subj, body)
def inline_form(self, which, form=None, ctx=None): """ Inline a form inside any template :param which: which macro to use, where there is a corresponding configuration variable e.g. specify 'login' where config value 'login_form' exists(see _default_forms above) :param form: optional, designate a specific form to use within the macro :param ctx: optional, a dict with specific context variables to use e.g. within in a another template {{ security.inline_form('change_password') }} or {{ security.inline_form('login', MyLoginForm, {'myvar': 12345}) }} """ m = self.which_macro(which) if m: mform, mwhere, mname = m[0], m[1], m[2] t = get_template_attribute(mwhere, mname) t_ctx = _Ctx() t_ctx.update(**self._run_ctx_processor(_endpoint)) t_ctx.update(macro=t) if form: t_ctx.update(form=form(request.form)) else: t_ctx.update(form=m[0](request.form)) if ctx: t_ctx.update(**ctx) return t(t_ctx)
def probe(): url = request.values.get('url') if not url or not is_safe_url(url): abort(400) results = probe_url(url) func = get_template_attribute('_results.html', 'render_results') return func(url, results)
def test_indicator(app: Flask, example_ledger: FavaLedger) -> None: with app.test_request_context(""): macro = get_template_attribute("macros/_account_macros.html", "indicator") assert macro(example_ledger, "NONEXISTING") == "" yellow_status = macro(example_ledger, "Assets:US:BofA:Checking") assert "yellow" in yellow_status
def autolink(self, link, is_email): if is_email: return '<a href="mailto:{0}">{0}</a>'.format(link) # analyze url parsed = urlparse(link) if 'youtube.com' in parsed.netloc: vid_id = dict(item.split('=') for item in parsed.query.split('&'))['v'] return youtube_embed(vid_id) if 'youtu.be' in parsed.netloc: vid_id = parsed.path return youtube_embed(vid_id) if parsed.path.lower().endswith(('.jpg', '.jpeg', '.jpe', '.jif', '.jfif', '.jfi', '.gif', '.png')): return '<a href="{0}"><img src="{0}" class="img-responsive img-thumbnail" /></a>'.format( link) # standard case autolink res = requests.get(link) soup = BeautifulSoup(res.text, 'html.parser') title = soup.title.string if len(title) > 50: title = title[:47] + '...' icon = soup.find("link", rel="shortcut icon") if icon: icon = icon['href'] # might be not absolute if not icon.startswith('http'): # url might have changed parsed = urlparse(res.url) if not icon.startswith('/'): icon = '/' + icon icon = parsed.scheme + '://' + parsed.netloc + icon render_autolink = get_template_attribute('macros.html', 'render_autolink') return render_autolink(link, title, icon).unescape()
def loading_interesting_topics(): """加载感兴趣的话题""" config = current_app.config _type = request.args.get('type') offset = request.args.get('offset', type=int) if not offset or not _type: return {'result': False} if _type == 'hot': topics = Topic.query.order_by(Topic.questions_count.desc()) elif _type == 'product': topics = Topic.query.get_or_404(config.get('PRODUCT_TOPIC_ID')).descendant_topics elif _type == 'organization': topics = Topic.query.get_or_404(config.get('ORGANIZATION_TOPIC_ID')).descendant_topics elif _type == 'position': topics = Topic.query.get_or_404(config.get('POSITION_TOPIC_ID')).descendant_topics elif _type == 'skill': topics = Topic.query.get_or_404(config.get('SKILL_TOPIC_ID')).descendant_topics else: topics = Topic.other_topics() topics = topics.limit(INTERESTING_TOPICS_PER).offset(offset) topics_count = topics.count() macro = get_template_attribute("macros/_account.html", "render_interesting_topics") return {'result': True, 'html': macro(topics), 'count': topics_count}
def create_tile(): dashboard_id = request.get_json()['dashboard_id'] report_id = request.get_json().get('report_id') report_instance_id = request.get_json().get('report_instance_id') tile_config = request.get_json()['tile_config'] moveresize = request.get_json()['moveresize'] for_layout_id = request.get_json()['for_layout_id'] check_access(lambda: auth.access_dashboard(dashboard_id)) check_access(lambda: auth.access_report_instances(report_id)) if tile_config['tags']: tile_config['tile_options']['tpcreator_uispec'] = tpcreator.suggested_tpcreator_uispec( tile_config['tags']) tile = tiles.Tile.insert(auth.logged_owner_id(), report_id, dashboard_id, tile_config) mres = layouts.place_tile(tile, for_layout_id=for_layout_id) if not mres: return error(message='Could not place the new tile on the dashboard, a page refresh is needed') dataseries.update_default_options(tile) log.info('Created new tile report_id=%s dashboard_id=%s tile_id=%s', report_id, dashboard_id, tile.tile_id) tile_html = get_template_attribute('m.html', 'dashboard_tile')\ (tile.tile_id, mres.new_tiles[tile], moveresize) return success(result=dict( tile_html=tile_html, new_layout_id=mres.new_layout.layout_id, ))
def add_resources_modal(): dataset = logic.dataset.find(request.args['owner'], request.args['name']) require.dataset.add_resource(dataset) resources = logic.resource.list_by_owner(current_user.name) modal = get_template_attribute('resource/parts.html', 'add_resources_modal') return modal(dataset, resources)
def db_detail(db=0): db_summary = server.keyspace.get(f"db{db}", dict()) cursor = request.args.get("cursor", type=int, default=0) keypattern = request.args.get("keypattern", default="") # when search, use bigger paginate number count = 1000 if keypattern else 30 key_details, next_cursor = _get_db_details( server.connection, db, cursor=cursor, keypattern=keypattern, count=count ) if cursor == 0: # render index page return render_template( "database.html", db_summary=db_summary, key_details=key_details, cursor=next_cursor, db=db, badge_style=BADGE_STYLE, keypattern=keypattern, ) macro = get_template_attribute("macros.html", "render_key_details") html = macro(key_details, db, BADGE_STYLE) url = "" if next_cursor != 0: url = url_for( "redisboard.db_detail", db=db, cursor=next_cursor, keypattern=keypattern ) return jsonify({"code": 0, "html": html, "data": url})
def test_modal_causative(app, case_obj, institute_obj, variant_obj): # GIVEN an initialized app with app.test_client() as client: # WHILE collection a specific jinja macro macro = get_template_attribute("variants/utils.html", "modal_causative") # and passing to it the required parameters # Including a case without HPO phenotype or diagnosis (OMIM terms) assigned html = macro(case_obj, institute_obj, variant_obj) # THEN the macro should contain the expected warning message assert "Assign at least an OMIM diagnosis or a HPO phenotype term" in html # WHEN the case contains one or more phenotype terms: case_obj["phenotype_terms"] = { "phenotype_id": "HPO:0002637", "feature": "Cerebral ischemia", } # and/or OMIM diagnoses case_obj["diagnosis_phenotypes"] = [616833] # THEN the macro should allow to assign partial causatives html = macro(case_obj, institute_obj, variant_obj) assert "Assign at least an OMIM diagnosis or a HPO phenotype term" not in html
def test_render_currency(app, example_ledger) -> None: with app.test_request_context(""): macro = get_template_attribute(COMMODITY_MACROS_PATH, "render_currency") assert "US Dollar" in macro(example_ledger, "USD") test = '<span title="TEST">TEST</span>' assert macro(example_ledger, "TEST") == test
def post_publish(chart_id): """ Publish the chart. :param chart_id: chart's unique identifier """ chart = Chart.objects.get(id=chart_id) if not chart.can_user_access(current_user): return return_json_error('Access Denied', 500) if request.method == 'POST': request_json = request.get_json() print 'saving json:' #print request_json.get('s3') chart.publish(current_user, request_json.get('options_id'), request_json.get('data_id'), request_json.get('s3')) if chart.is_published: chart_embed_script = get_template_attribute('macros_chart.html', 'chart_embed_script') response = { 'message': 'Successfully uploaded to S3', 'published_obj': chart.published_obj.to_dict(), 'url_2300': chart.get_image_2300_url(), 'embed_code': chart_embed_script(chart), } return Response(response=json.dumps(response), status=200, mimetype="application/json") else: return return_json_error('Publish failed', 500)
def unfollow(type, id): """ Removes current user as follower Returns JSON """ if type == 'collection': model = Collection.objects.get_or_404(id=id) elif type == 'queue': model = Queue.objects.get_or_404(id=id) elif type == 'maker': model = Maker.objects.get_or_404(id=id) elif type == 'thread': model = Thread.objects.get_or_404(id=id) elif type == 'thing': model = Thing.objects.get_or_404(id=id) else: abort(404) user = User.objects(id=current_user.get_id()).first() model.remove_follower(user) if type == 'collection': cached = Cache.objects(name="collections-for-%s" % current_user.get_id()).first() if cached: cached.delete() return jsonify({ 'result': 'success', 'message': unicode(get_template_attribute('frontend/macros.html', 'follow')(model)) })
def get_more(): """Handles requests for more post and submissions when a user presses "Show more" """ start = int(request.form.get("start")) rendered_posts = [] template = get_template_attribute('partials/_post.html', "post_template") posts = [] page = request.form.get("page") if page == "home": status = request.form.get("status") if status == "open": posts = Post.get_open_posts(start) if status == "closed": posts = Post.get_closed_posts(start) if status == "archived": posts = Post.get_archived_posts(start) if page == "search": query, difficulty, tag = parse_search_query(request.form.get("query")) posts = Post.get_searched_posts(query, difficulty=difficulty, tag=tag, start=start) if posts: for post in posts: post_html = template(page=page, post=post) rendered_posts += [post_html] return jsonify({ "success": True, "posts": rendered_posts }) else: return jsonify({ "success": False })
def add_to_collection(uid): piece = Piece.query.get_or_404(uid) title = request.form.get("title") collection_id = request.form.get("collection_id") collection = None if title: collection = Collection.get_by_title(title, create_if_not_exist=True) elif collection_id: collection = Collection.query.get_or_404(collection_id) if not collection: abort(404) # 若该句集尚未收录此句子,则收录 collection_piece = CollectionPiece.query.filter( CollectionPiece.collection_id == collection.id, CollectionPiece.piece_id == uid ).first() if not collection_piece: collection_piece = CollectionPiece(collection_id=collection.id, piece_id=uid) # log log = PieceEditLog( piece_id=uid, user_id=g.user.id, after=collection.title, after_id=collection.id, kind=PIECE_EDIT_KIND.ADD_TO_COLLECTION, ) db.session.add(collection_piece) db.session.add(log) db.session.commit() macro = get_template_attribute("macros/_collection.html", "render_collection_tag_wap") return json.dumps({"result": True, "id": collection.id, "html": macro(collection)})
def modal(uid): piece = Piece.query.get_or_404(uid) piece.clicks_count += 1 db.session.add(piece) db.session.commit() modal = get_template_attribute("macros/_piece.html", "render_piece_details_wap") return modal(piece)
def comment(uid): """评论""" piece = Piece.query.get_or_404(uid) content = request.form.get("comment") root_comment_id = request.form.get("root_comment_id", type=int) target_user_id = request.form.get("target_user_id", type=int) if not content: abort(500) comment = PieceComment(content=content.strip(), piece_id=uid, user_id=g.user.id) if root_comment_id: # 若该评论为sub comment root_comment = PieceComment.query.get_or_404(root_comment_id) target_user = User.query.get_or_404(target_user_id) comment.root_comment_id = root_comment_id comment.target_user_id = target_user_id db.session.add(comment) db.session.commit() if root_comment_id: noti_receiver_id = target_user_id noti_kind = NOTIFICATION_KIND.COMMENT_PIECE_COMMENT else: noti_receiver_id = piece.user_id noti_kind = NOTIFICATION_KIND.COMMENT_PIECE # 推送通知 if noti_receiver_id != g.user.id: noti = Notification( sender_id=g.user.id, target=piece.content, content=content, receiver_id=noti_receiver_id, kind=noti_kind, link="%s#comment_%d" % (url_for("piece.view", uid=uid), comment.id), ) db.session.add(noti) db.session.commit() # 返回comment HTML comment_macro = get_template_attribute("macros/_piece.html", "render_piece_comment") sub_comments_macro = get_template_attribute("macros/_piece.html", "render_piece_sub_comments") comment_html = comment_macro(comment) # 若为root comment,则在返回的HTML中加入sub_comments if not root_comment_id: comment_html += sub_comments_macro(comment) return comment_html
def process_cobbler_object(objects, item_name): if objects not in ["distros", "profiles", "systems", "kickstarts"]: return predefined = cobbler_default_data[objects] url_prefix = "/cm/v1/cobbler" url = "{0}/{1}/{2}".format(url_prefix, objects, item_name) method = request.method.lower() template = "" if method == "get": result = request_rest_api(method, url) else: result = request_rest_api(method, url, request.json) if result["result"] and method == "post": result = request_rest_api("get", url) if result["result"] and method in ["get", "post"]: append_select_data(objects, result) if predefined["flag_collection"]: accordion_panel = get_template_attribute("mesh/cobbler/cobbler_macro.html", "CM_ACCORDION_PANEL_COLLECTION") result["template"] = accordion_panel( objects, result["data"][0]["data"], predefined["field_filter"]["normal"], predefined["button"]["normal"], predefined["field_filter"], ) else: accordion_panel = get_template_attribute("mesh/cobbler/cobbler_macro.html", "CM_ACCORDION_PANEL") result["template"] = accordion_panel( objects, result["data"][0]["data"], predefined["field_filter"]["normal"], predefined["button"]["normal"] ) if method == "post": if predefined["flag_collection"]: accordion_panel_add = get_template_attribute( "mesh/cobbler/cobbler_macro.html", "CM_ACCORDION_PANEL_COLLECTION" ) add_data = get_add_data_dict(objects, result) add_template = accordion_panel_add( objects, add_data["data"], add_data["filter"], add_data["button"], predefined["field_filter"], True ) else: accordion_panel_add = get_template_attribute("mesh/cobbler/cobbler_macro.html", "CM_ACCORDION_PANEL") add_data = get_add_data_dict(objects, result) add_template = accordion_panel_add( objects, add_data["data"], add_data["filter"], add_data["button"], True ) result["template"] += add_template return Response(json.dumps(result), status=200, mimetype="application/json")
def list(case_id): if current_user.is_anonymous(): return redirect(url_for("components.index", case_id=case_id)) # FIXME Shouldn't be an abort() ? components = [] # TODO render = get_template_attribute("components.jinja2", "render") return render_list(g, current_user, components)
def add_datasets_modal(): resource = logic.resource.find(request.args['owner'], request.args['name']) require.dataset.create(current_user) datasets = logic.dataset.list_by_owner(current_user.name) modal = get_template_attribute('dataset/parts.html', 'add_datasets_modal') return modal(resource, datasets)
def admin_add_classes(): if request.path.endswith('.json'): car = get_template_attribute('/admin/admin_widgets.html', 'calsses_table') #get macro in a template categories = car(categories=dw.get_all_category(), ajax=True) return jsonify(categories) #flask.json.jsonify(*args, **kwargs) else: car = dw.get_all_category() return render_template("admin/admin_classes.html",categories=car)
def similar(): """类似问题""" title = request.form.get('title') if not title: return "" similar_questions, total, took = Question.query_from_es(title, only_title=True, page=1, per_page=5) macro = get_template_attribute('macros/_question.html', 'similar_questions') return {'count': len(similar_questions), 'html': macro(similar_questions)}
def modal(uid): piece = Piece.query.get_or_404(uid) piece.clicks_count += 1 db.session.add(piece) db.session.commit() modal = get_template_attribute('macros/_piece.html', 'render_piece_details_wap') return modal(piece)
def test_balance_directive(app: Flask, example_ledger: FavaLedger) -> None: today = datetime.date.today() bal = f"{today} balance Assets:US:BofA:Checking 1632.79 USD\n" with app.test_request_context(""): macro = get_template_attribute("macros/_account_macros.html", "balance_directive") assert macro(example_ledger, "NONEXISTING") == "" assert macro(example_ledger, "Assets:US:BofA:Checking") == f"{bal}"
def render(self): render = render_template_string e = self.entry manager = render( u'<img class="avatar" ' u'src="{{ user_photo_url(user=e.manager, size=16) }}" alt="" />' u'<a href="''{{ url_for("social.user", user_id=e.manager.id) }}">' u'{{ e.manager.name }}</a>', e=e) if self.entry.user: principal = render(self._USER_FMT, user=self.entry.user) elif self.entry.group: principal = render(self._GROUP_FMT, group=self.entry.group) else: principal = u'' entity = u'' if e.object_id: entity_url = None entity_name = e.object_name if e.object: entity_name = getattr(e.object, 'path', e.object.name) entity_url = url_for(e.object) entity = render( u'{%- if url %}<a href="{{ url }}">{%- endif %}' u'{{ name }}{%- if url %}</a>{%- endif %}', url=entity_url, name=entity_name) if e.op == e.SET_INHERIT: msg = _(u'{manager} has activated inheritance on {entity}') elif e.op == e.UNSET_INHERIT: msg = _(u'{manager} has deactivated inheritance on {entity}') elif e.op == e.GRANT: msg = _(u'{manager} has given role "{role}" to {principal} ' 'on {entity}') elif e.op == e.REVOKE: msg = _(u'{manager} has revoked role "{role}" from ' '{principal} on {entity}') else: raise Exception("Invalid entity op: {}".format(e.op)) else: if e.op == e.GRANT: msg = _(u'{manager} has given role "{role}" to {principal}') elif e.op == e.REVOKE: msg = _(u'{manager} has revoked role "{role}" from {principal}') else: raise Exception("Invalid entity op: {}".format(e.op)) self.msg = Markup(msg.format(manager=manager, principal=principal, role=e.role, entity=entity)) tmpl = get_template_attribute('admin/_macros.html', 'm_security_entry') return tmpl(self)
def fetch_report_list(): filter_s = request.get_json().get('filter_s') last_report_id = request.get_json().get('last_report_id') check_access(lambda: auth.access_profile()) report_list = _report_list(filter_s, last_report_id) html = get_template_attribute('m.html', 'reports_list_page')(report_list, filter_s, len(report_list) == REPORTS_PER_PAGE) return success(result=dict(html=html))
def get_edit_form(): page = request.form.get("page") edit_data = { "section": request.form.get("section"), "images": get_available_images() } form = get_template_attribute('edit_content.html', request.form.get("type")) return form(page, fetch_page_content(page), edit_data)
def add_topic(uid): """添加话题""" question = Question.query.get_or_404(uid) topic_id = request.form.get('topic_id', type=int) name = request.form.get('name', '').strip() if topic_id is None and name == "": return {'result': False} topic = None if name: topic = Topic.get_by_name(name, user_id=g.user.id, create_if_not_exist=True) else: topic = Topic.query.get_or_404(topic_id) if not topic: abort(404) # 添加话题 question_topic = QuestionTopic.query.filter( QuestionTopic.topic_id == topic.id, QuestionTopic.question_id == uid).first() if question_topic: return {'result': False} question_topic = QuestionTopic(topic_id=topic.id, question_id=uid) # Log log = PublicEditLog(question_id=uid, user_id=g.user.id, after=topic.name, after_id=topic.id, kind=QUESTION_EDIT_KIND.ADD_TOPIC) db.session.add(log) db.session.add(question_topic) # MERGE: 若该话题被合并到其他话题,则也对此问题添加 merge_to_topic if topic.merge_to_topic_id: question_merge_to_topic = topic.merge_to_topic.questions.filter(QuestionTopic.question_id == uid).first() if not question_merge_to_topic: question_merge_to_topic = QuestionTopic(topic_id=topic.merge_to_topic_id, question_id=uid, from_merge=True) db.session.add(question_merge_to_topic) db.session.commit() # 更新话题统计数据 answer = question.answers.filter(Answer.user_id == g.user.id).first() if answer: UserTopicStatistic.add_answer_in_topic(g.user.id, topic.id) if answer.upvotes_count > 0: UserTopicStatistic.upvote_answer_in_topic(g.user.id, topic.id, answer.upvotes_count) topic.questions_count += 1 topic.updated_at = datetime.now() db.session.add(topic) db.session.commit() macro = get_template_attribute('macros/_topic.html', 'topic_wap') return {'result': True, 'id': topic.id, 'html': macro(topic)}
def submit_product_worked_on(): """提交工作过的产品""" name = request.form.get('name') topic_id = request.form.get('topic_id') topic = None if name: topic = Topic.get_by_name(name, user_id=g.user.id, create_if_not_exist=True) elif topic_id: topic = Topic.query.get_or_404(topic_id) # 添加产品 product = WorkOnProduct.query.filter( WorkOnProduct.topic_id == topic.id, WorkOnProduct.user_id == g.user.id).first() if product: return {'result': False} else: product = WorkOnProduct(topic_id=topic.id, user_id=g.user.id) db.session.add(product) # 自动关注话题 follow_topic = FollowTopic.query.filter(FollowTopic.topic_id == topic.id, FollowTopic.user_id == g.user.id).first() if not follow_topic: follow_topic = FollowTopic(topic_id=topic.id, user_id=g.user.id) db.session.add(follow_topic) topic.followers_count += 1 db.session.add(topic) # USER FEED: 关注话题 UserFeed.follow_topic(g.user, topic) # 在 UserTopicStatistic 中标记该话题 topic_statistic = UserTopicStatistic.query.filter(UserTopicStatistic.topic_id == topic.id, UserTopicStatistic.user_id == g.user.id).first() if topic_statistic: topic_statistic.worked_on = True else: topic_statistic = UserTopicStatistic(topic_id=topic.id, user_id=g.user.id, worked_on=True) db.session.add(topic_statistic) db.session.commit() new_topic = name is not None and name != "" if new_topic: upload_token = qiniu.generate_token(policy={ 'callbackUrl': absolute_url_for('topic.update_avatar'), 'callbackBody': "id=%d&key=$(key)" % topic.id }) else: upload_token = "" macro = get_template_attribute('macros/_account.html', 'render_product_worked_on') return {'result': True, 'html': macro(product, new_topic, upload_token)}
def load_posts(): """加载文章""" page = request.form.get('page', 1, type=int) posts = Post.query.filter(~Post.hide).filter(Post.blog.has(Blog.is_approved)).order_by( Post.published_at.desc()).paginate(page, LATEST_POSTS_PER).items macro = get_template_attribute('macro/ui.html', 'render_latest_posts') return json.dumps({ 'result': True, 'html': macro(posts) })
def render(name): # TODO: find a better way if name == 'api_request': spac = Spac.get_spac(session['id']) return spac.send_api_key(request.values['email']) from flask import get_template_attribute m = get_template_attribute('render.html', name) result = m(**dict(request.values.iteritems())) return make_response(result)
def list_for_thing(thing_id): """ A list of collections and optional form """ thing = Thing.objects.get_or_404(id=thing_id) collections = Collection.objects.filter(things__thing=thing) # Add this thing to one or more collections if can_add_thing_to_collections(): cf = AddThingToCollectionsForm(formdata=request.form) cf.set_thing(thing) if cf.validate_on_submit(): ct = CollectedThing() cf.populate_obj(ct) cf.collection.data.add_thing(ct) form_template = get_template_attribute( 'collection/macros.html', 'add_to_collection_form')(cf) return get_template_attribute('collection/macros.html', 'show_collections_list')(collections, thing, form_template) else: return get_template_attribute('collection/macros.html', 'show_collections_list')(collections, thing)
def loading_followed_questions(): """加载关注的问题""" offset = request.args.get('offset', type=int) if not offset: return {'result': False} questions = g.user.followed_questions.limit(FOLLOWED_QUESTIONS_PER).offset(offset) count = questions.count() macro = get_template_attribute("macros/_user.html", "render_followed_questions") return {'result': True, 'html': macro(questions), 'count': count}