Python Flask module and pythonflask Module

Source: Internet
Author: User

Python Flask module and pythonflask Module

The module is a file containing response text, which contains the dynamic part represented by a space variable. The specific value is only known in the request context. Replace the variable with the actual value and return the final response string. This process is called rendering. To render the module, Flask uses a powerful template engine named Jinja2.

 

I. Jinja2 template engine

The simplest Jinja2 template is a file containing the response text.

1. Rendering Template

By default, Flask searches for templates in the templates subfolders in the program folder. .

#!/usr/bin/env pythonfrom flask import Flask,render_templateapp = Flask(__name__)@app.route('/')def index():    return render_template('index.html')@app.route('/user/<name>')def user(name):    return render_template('user.html',name=name)if __name__ == '__main__':    app.run()

The render_template function provided by Flask integrates the Jinja module engine into the program.

 

2. Variables

The {name} structure used in the template represents a variable. It is a special placeholder that tells the template engine to obtain the value of this position from the data used in the rendering template.

Jinja2 can recognize all types of variables, or even complex types, such as lists, dictionaries, and objects. Examples of variables used in the template are as follows:

<p>a value from a dictionary: {{ mydict['key'] }}</p><p>a value from a list:{{ mylist[3] }}</p><p>a value from a list,with a varliable index:{{ mylist[myintavr] }}</p><p>a value from a objects method:{{ myobj.somemethod() }}</p>

Jinja2 Variable Filter

Filter Name Description
Safe , Do not escape during rendering
Capitalize
Converts an uppercase letter to a lowercase letter.
Lower Converts a value to lowercase.
Upper Converts a value to a large write format.
Title Converts the initial letter of each word in the value to uppercase.
Trim Remove the first space of the value
Striptags Delete all HTML tags in the value before rendering

 

3. Control Structure

Use the conditional control statement in the template:

{% if user %}    Hello,{{ user }}!{% else %}    Hello,Stranger!{% endif %}
<ul>    {% for commet in commets %}        <li>{{ commet }}</li>    {% end for %}</ul>

Jinja2 also supports macros, similar to functions in Python code. For example:

{% macro render_commet(commet) %}    <li>{{ commet }}</li>{% endmacro %}<ul>    {% for commet in commets %}        {{ render_commet(commet) }}    {% endfor %}</ul>

To reuse macros, we can save them in a separate file and import them in the template to be used:

{% import 'macros.html' as macros %}<ul>    {% for commet in commets %}        {{ macros.render_commet(commet) }}    {% endfor %}</ul>

Another powerful way to reuse code is template inheritance, which is similar to class inheritance in Python code. First, create a base template named base.html:

 

2. Integrate Twitter Bootstrp with Flask-Bootstrap

Bootstrap is a client architecture, so it does not directly involve servers. The server provides HTML responses that reference the Bootstrap Cascading Style Sheet (CSS) and Javascript files, and instantiate required components in HTML/CSS and Javascript code. The most ideal place for these operations is the template.

# Initialize Flask-bootstrapfrom flask. ext. bootstrap import Bootstrap #... bootstrap = Bootstrap (app)

After Flask-Bootstrap is initialized, a base template containing all Bootstrap files can be used in the program.

{% extends "bootstrap/base.html" %}{% block title %}Flasky{% endblock %}{% block navbar %}<div class="navbar navbar-inverse" role="navigation">    <div class="container">        <div class="navbar-header">            <button type="button" class="navbar-toggle"            data-toggle="collapse" data-target=".navbar-collapse">                <span class="sr-only">Toggle navigation</span>                <span class="icon-bar"></span>                <span class="icon-bar"></span>                <span class="icon-bar"></span>            </button>            <a class="navbar-brand" href="/">Flasky</a>        </div>        <div class="navbar-collapse collapse">            <ul class="nav navbar-nav">                <li><a href="/">Home</a></li>            </ul>        </div>    </div></div>{% endblock %}{% block content %}<div class="container">    <div class="page-header">        

 

3. custom error page
# Custom error page #! /Usr/bin/env pythonfrom flask import Flask, render_templateapp = Flask (_ name _) @ app. errorhandler (404) def page_not_found (e): return render_template('404.html '), 404@app.errorhandler (500) def internal_server_error (e): return render_template('500.html '), 500if _ name _ = '_ main _': app. run ()

 

4. Links

Flask provides the url_for () auxiliary function, which can generate a URL using the information saved in the program URL ing.

The simplest usage of url_for () is to use the view function name (or the endpoint name used when app. add_url_route () defines the route) as the parameter and return the corresponding URL.

When url_for () is used to generate a dynamic address, the dynamic part is passed in as a keyword parameter. For example, url_for ('user', name = 'john', _ external = True)

 

5. static files

By default, Flask searches for static files in the subdirectory named static in the root directory of the program. If necessary, you can use subfolders in the static folder to store files.

# Define the favorites icon {% block head % }{{ super () }}< link rel = "shortcut icon" href = "{url_for ('static ', filename = 'favicon. ico ')} "type =" image/x-icon "> <link rel =" icon "href =" {url_for ('static', filename = 'favicon. ico ')} "type =" image/x-icon ">{% endblock %}

 

6. Use Flask-Moment to localize the date and time

Flask-Moment is a Flask program extension that can integrate moment. js into the Jinja2 template.

# Initialize Flask-Momentfrom flask. ext. moment import Momentmoment = Moment (app)
# Introduce the moment. js library {% block scripts % }{{ super () }{{ moment. include_moment () }}{% endblock %}
#!/usr/bin/env pythonfrom flask import Flask,render_templateapp = Flask(__name__)from datetime import datetimefrom flask_moment import Momentmoment = Moment(app)@app.route('/')def index():    return render_template('index.html',                           current_time=datetime.utcnow())if __name__ == '__main__':    app.run()

  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.