Python flask.render_template() Examples

The following are 30 code examples of flask.render_template(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask , or try the search function .
Example #1
Source File: rl_data.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 14 votes vote down vote up
def make_web(queue):
    app = Flask(__name__)

    @app.route('/')
    def index():
        return render_template('index.html')

    def gen():
        while True:
            frame = queue.get()
            _, frame = cv2.imencode('.JPEG', frame)
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame.tostring() + b'\r\n')

    @app.route('/video_feed')
    def video_feed():
        return Response(gen(),
                        mimetype='multipart/x-mixed-replace; boundary=frame')

    try:
        app.run(host='0.0.0.0', port=8889)
    except:
        print('unable to open port') 
Example #2
Source File: web.py    From svviz with MIT License 7 votes vote down vote up
def index():
    if not "last_format" in session:
        session["last_format"] = "svg"
        session.permanent = True

    try:
        variantDescription = str(dataHub.variant).replace("::", " ").replace("-", "–")
        return render_template('index.html',
            samples=list(dataHub.samples.keys()), 
            annotations=dataHub.annotationSets,
            results_table=dataHub.getCounts(),
            insertSizeDistributions=[sample.name for sample in dataHub if sample.insertSizePlot], 
            dotplots=dataHub.dotplots,
            variantDescription=variantDescription)
    except Exception as e:
        logging.error("ERROR:{}".format(e))
        raise 
Example #3
Source File: views.py    From everyclass-server with Mozilla Public License 2.0 6 votes vote down vote up
def show_review(cotc_id: int):
    """查看某个教学班的评价"""
    cotc_id = int(cotc_id)

    review_info = CourseReview.get_review(cotc_id)
    avg_rate = review_info['avg_rate']
    reviews = review_info['reviews']

    cotc = COTeachingClass.get_doc(cotc_id)
    if not cotc:
        return render_template('common/error.html', message=MSG_404)

    if session.get(SESSION_CURRENT_USER, None) \
            and CourseReview.get_my_review(cotc_id=cotc_id, student_id=session[SESSION_CURRENT_USER].identifier):
        reviewed_by_me = True
    else:
        reviewed_by_me = False
    return render_template('course/review.html',
                           cotc=cotc,
                           count=review_info['count'],
                           avg_rate=avg_rate,
                           reviews=reviews,
                           user_is_taking=is_taking(cotc),
                           reviewed_by_me=reviewed_by_me) 
Example #4
Source File: views.py    From everyclass-server with Mozilla Public License 2.0 6 votes vote down vote up
def main():
    """用户主页"""
    try:
        is_student, student = entity_service.get_people_info(session[SESSION_CURRENT_USER].identifier)
        if not is_student:
            return "Teacher is not supported at the moment. Stay tuned!"
    except Exception as e:
        return handle_exception_with_error_page(e)

    pending_grant_reqs = user_service.get_pending_requests(session[SESSION_CURRENT_USER].identifier)
    pending_grant_names = []
    for req in pending_grant_reqs:
        pending_grant_names.append(entity_service.get_people_info(req.user_id)[1].name)

    return render_template('user/main.html',
                           name=session[SESSION_CURRENT_USER].name,
                           student_id_encoded=session[SESSION_CURRENT_USER].identifier_encoded,
                           last_semester=student.semesters[-1] if student.semesters else None,
                           privacy_level=user_service.get_privacy_level(session[SESSION_CURRENT_USER].identifier),
                           pending_grant_names=pending_grant_names) 
Example #5
Source File: paint.py    From unicorn-hat-hd with MIT License 5 votes vote down vote up
def home():
    return render_template('painthathd.html') 
Example #6
Source File: app.py    From wechatpy with MIT License 5 votes vote down vote up
def index():
    host = request.url_root
    return render_template("index.html", host=host) 
Example #7
Source File: app.py    From wechatpy with MIT License 5 votes vote down vote up
def index():
    host = request.url_root
    return render_template("index.html", host=host) 
Example #8
Source File: app.py    From wechatpy with MIT License 5 votes vote down vote up
def index():
    host = request.url_root
    return render_template("index.html", host=host) 
Example #9
Source File: views.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def get_classroom(url_rid, url_semester):
    """教室查询"""
    # decrypt identifier in URL
    try:
        _, room_id = decrypt(url_rid, resource_type='room')
    except ValueError:
        return render_template("common/error.html", message=MSG_INVALID_IDENTIFIER)
    # todo 支持没有学期的room
    # RPC to get classroom timetable
    try:
        room = entity_service.get_classroom_timetable(url_semester, room_id)
    except Exception as e:
        return handle_exception_with_error_page(e)

    with tracer.trace('process_rpc_result'):
        cards = defaultdict(list)
        for card in room.cards:
            day, time = lesson_string_to_tuple(card.lesson)
            cards[(day, time)].append(card)

    empty_5, empty_6, empty_sat, empty_sun = _empty_column_check(cards)

    available_semesters = semester_calculate(url_semester, room.semesters)

    return render_template('entity/room.html',
                           room=room,
                           cards=cards,
                           empty_sat=empty_sat,
                           empty_sun=empty_sun,
                           empty_6=empty_6,
                           empty_5=empty_5,
                           available_semesters=available_semesters,
                           current_semester=url_semester) 
Example #10
Source File: views.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def get_card(url_cid: str, url_semester: str):
    """课程查询"""
    # decrypt identifier in URL
    try:
        _, card_id = decrypt(url_cid, resource_type='klass')
    except ValueError:
        return render_template("common/error.html", message=MSG_INVALID_IDENTIFIER)

    # RPC to get card
    try:
        card = entity_service.get_card(url_semester, card_id)
    except Exception as e:
        return handle_exception_with_error_page(e)

    day, time = lesson_string_to_tuple(card.lesson)

    # cotc_id = COTeachingClass.get_id_by_card(card)
    # course_review_doc = CourseReview.get_review(cotc_id)

    return render_template('entity/card.html',
                           card=card,
                           card_day=get_day_chinese(day),
                           card_time=get_time_chinese(time),
                           # cotc_id=cotc_id,
                           # cotc_rating=course_review_doc["avg_rate"],
                           cotc_id=0,
                           cotc_rating=0,
                           current_semester=url_semester
                           ) 
Example #11
Source File: views.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def available_rooms():
    return render_template("entity/available_rooms.html") 
Example #12
Source File: views.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def electives():
    return render_template('course/electives.html') 
Example #13
Source File: views.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def elective_assistant():
    return render_template('course/elective_assistant.html') 
Example #14
Source File: web_helpers.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def disallow_in_maintenance(func):
    """
    a decorator for routes which should be unavailable in maintenance mode.
    """

    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        config = get_config()
        if config.MAINTENANCE:
            return render_template('maintenance.html')
        return func(*args, **kwargs)

    return wrapped 
Example #15
Source File: web_helpers.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def login_required(func):
    """
    a decorator for routes which is only available for logged-in users.
    """

    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        if not session.get(SESSION_CURRENT_USER, None):
            return render_template('common/error.html', message=MSG_NOT_LOGGED_IN, action="login")
        return func(*args, **kwargs)

    return wrapped 
Example #16
Source File: web_helpers.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def _error_page(message: str, sentry_capture: bool = False, log: str = None):
    """return a error page with a message. if sentry is available, tell user that they can report the problem."""
    sentry_param = {}
    if sentry_capture and plugin_available("sentry"):
        sentry.captureException()
        sentry_param.update({"event_id": g.sentry_event_id,
                             "public_dsn": sentry.client.get_public_dsn('https')
                             })
    if log:
        logger.info(log)
    return render_template('common/error.html', message=message, **sentry_param) 
Example #17
Source File: web_helpers.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def check_permission(student: StudentTimetableResult) -> Tuple[bool, Optional[str]]:
    """
    检查当前登录的用户是否有权限访问此学生

    :param student: 被访问的学生
    :return: 第一个返回值为布尔类型,True 标识可以访问,False 表示没有权限访问。第二个返回值为没有权限访问时需要返回的模板
    """
    can, reason = user_service.has_access(student.student_id,
                                          session.get(SESSION_CURRENT_USER).identifier if session.get(SESSION_CURRENT_USER, None) else None)
    if reason == user_service.REASON_LOGIN_REQUIRED:
        return False, render_template('entity/studentBlocked.html',
                                      name=student.name,
                                      falculty=student.deputy,
                                      class_name=student.klass,
                                      level=1)
    if reason == user_service.REASON_PERMISSION_ADJUST_REQUIRED:
        return False, render_template('entity/studentBlocked.html',
                                      name=student.name,
                                      falculty=student.deputy,
                                      class_name=student.klass,
                                      level=3)
    if not can:
        return False, render_template('entity/studentBlocked.html',
                                      name=student.name,
                                      falculty=student.deputy,
                                      class_name=student.klass,
                                      level=2)

    return True, None 
Example #18
Source File: views_main.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def main():
    """首页"""
    return render_template('common/index.html') 
Example #19
Source File: views_main.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def test():
    """首页"""
    time.sleep(5)
    return render_template('common/index.html') 
Example #20
Source File: views_main.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def guide():
    """帮助页面"""
    return render_template('common/guide.html') 
Example #21
Source File: views_main.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def testing():
    """测试页面"""
    return render_template('testing.html') 
Example #22
Source File: views_main.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def donate():
    """点击发送邮件后的捐助页面"""
    return render_template('common/donate.html') 
Example #23
Source File: views.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def register_by_email():
    """注册:第三步:使用邮箱验证注册"""
    if not session.get(SESSION_USER_REGISTERING, None):  # 步骤异常,跳回第一步
        return redirect(url_for('user.register'))

    identifier = session[SESSION_USER_REGISTERING].identifier

    try:
        request_id = user_service.register_by_email(identifier)
    except Exception as e:
        return handle_exception_with_error_page(e)
    else:
        return render_template('user/emailSent.html', request_id=request_id) 
Example #24
Source File: views.py    From everyclass-server with Mozilla Public License 2.0 5 votes vote down vote up
def pending_grants():
    """待处理的课表访问请求"""
    return render_template('user/pendingGrants.html') 
Example #25
Source File: document.py    From MPContribs with MIT License 5 votes vote down vote up
def post_delete(cls, sender, document, **kwargs):
        admin_email = current_app.config["MAIL_DEFAULT_SENDER"]
        admin_topic = current_app.config["MAIL_TOPIC"]
        subject = f'Your project "{document.project}" has been deleted'
        html = render_template(
            "owner_email.html", approved=False, admin_email=admin_email
        )
        topic_arn = ":".join(
            admin_topic.split(":")[:-1] + ["mpcontribs_" + document.project]
        )
        send_email(topic_arn, subject, html)
        sns_client.delete_topic(TopicArn=topic_arn) 
Example #26
Source File: main.py    From MPContribs with MIT License 5 votes vote down vote up
def home():
    return render_template("main.html") 
Example #27
Source File: webui.py    From MPContribs with MIT License 5 votes vote down vote up
def view(identifier=None, cid_short=None):
    mpfile = read_mpfile_to_view()
    if mpfile is None:
        return render_template("home.html", alert="Choose an MPFile!", session=session)
    fmt = session["options"][0]
    try:
        mpfile_stringio = StringIO(mpfile)
        if identifier is None or cid_short is None:
            response = Response(
                stream_with_context(
                    stream_template(
                        "index.html",
                        session=session,
                        content=process_mpfile(mpfile_stringio, fmt=fmt),
                    )
                )
            )
            response.headers["X-Accel-Buffering"] = "no"
            return response
        else:
            ids = [identifier, cid_short]
            iterator = process_mpfile(mpfile_stringio, fmt=fmt, ids=ids)
            for it in iterator:
                if isinstance(it, list):
                    d = jsonify(it)
            return d
    except Exception:
        pass 
Example #28
Source File: webui.py    From MPContribs with MIT License 5 votes vote down vote up
def load():
    mpfile = session.get("mpfile")
    if mpfile is None:
        return render_template("home.html", alert="Choose an MPFile!", session=session)
    input_mpfile_path = default_mpfile_path.replace(".txt", "_in.txt")
    with codecs.open(input_mpfile_path, encoding="utf-8", mode="w") as f:
        f.write(mpfile)
    return render_template("home.html", session=session) 
Example #29
Source File: server.py    From grlc with MIT License 5 votes vote down vote up
def api_docs_template():
    """Generate Grlc API page."""
    return render_template('api-docs.html', relative_path=relative_path()) 
Example #30
Source File: server.py    From grlc with MIT License 5 votes vote down vote up
def grlc():
    """Grlc landing page."""
    resp = make_response(render_template('index.html'))
    return resp

#############################
### Routes for local APIs ###
#############################

# Spec generation, front-end