Python Flask Module

Source: Internet
Author: User
Tags button type

A module is a file that contains the response text, which contains the dynamic portion of the placeholder variable representation, and its specific value is only known in the context of the request. Replace the variable with the real value and return the resulting response string, which is called rendering. To render the module, Flask uses a powerful template engine called JINJA2.

First, JINJA2 template engine

The simplest form of Jinja2 template is a file that contains the response text.

1. Render Template

By default, flask looks for templates in the Templates subfolder in the Programs folder. In the next hello.py release, save the previously defined templates in the Templates folder and name them index.html and user.html, respectively.

#!/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, which is a special placeholder that tells the template engine that the value of this location is obtained from the data used when rendering the template.

JINJA2 can identify all types of variables, even some complex types, such as lists, dictionaries, and objects. Some examples of using variables in templates 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 , rendering is not escaped
Capitalize
Convert a worthy first letter to uppercase, and other letters to lowercase
Lower Change the value to lowercase
Upper Convert a value to uppercase
Title Converts the first letter of each word in a value to uppercase
Trim Remove the first space in the value
Striptags Delete all HTML tags in the value before rendering

3. Control structure

To use conditional control statements in a 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 a macro, we can save it in a separate file and then import it in the template that we need to use:

{% 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 resembles class inheritance in Python code. Start by creating a base template named base.html:

Second, using Flask-bootstrap integrated Twitter BOOTSTRP

Bootstrap is a client-side schema and therefore does not directly involve the server. The server's knowledge provides an HTML response referencing the bootstrap cascading style sheets (CSS) and JavaScript files, and instantiates the required components in HTML/CSS and JavaScript code. The most ideal place to run these operations is the template.

#初始化 flask-bootstrapfrom flask.ext.bootstrap Import bootstrap#...bootstrap = Bootstrap (APP)

After you initialize Flask-bootstrap, you can use a base template that contains all the bootstrap files in your program.

{% extends "bootstrap/base.html"%} {% block title%} flasky{% endblock%}{% block navbar%}<div class= "NavBar navbar-inverse" role= "navigation" > <div class= "Contai Ner "> <div class=" Navbar-header "> <button type=" button "class=" Navbar-toggle "dat a-toggle= "Collapse" data-target= ". Navbar-collapse" > <span class= "sr-only" >toggle navigation</sp                 an> <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 C        lass= "Nav navbar-nav" > <li><a href= "/" >Home</a></li> </ul> </div> </div></div>{% endblock%}{% block content%}<div class= "conTainer "> <div class=" Page-header "> 

Third, custom error interface
#自定义错误界面 #!/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 (+) def internal_server_error (e):    return render_template (' 500.html '), 500if __name__ = = ' __main__ ':    app.run ()

Four: Links

Flask provides a url_for () helper function that generates a URL using information saved in the program's URL mapping.

The simplest use of the url_for () function is to return the corresponding URL as a parameter, using the name of the view function (or the end name that is used when defining the route App.add_url_route ()).

When generating a dynamic address using url_for (), the dynamic part is passed in as a keyword parameter. For example, url_for (' user ', Name= ' John ', _external=true)

V. Static files

By default, flask looks for a static file in a subdirectory named static in the program root directory. If you want, you can use subfolders to hold files in the static folder.

#定义收藏夹图标 {% block Head%}{{super ()}}<link rel= "shortcut icon" href= "{{url_for (' static ', filename= ' Favicon.ico ')}}" C0/>type= "Image/x-icon" ><link rel= "icon" href= "{{url_for (' static ', filename= ' Favicon.ico ')}}"    type= " Image/x-icon ">{% endblock%}

Vi. using Flask-moment to localize dates and times

Flask-moment is a Flask program extension that integrates moment.js into JINJA2 templates.

#初始化Flask-momentfrom flask.ext.moment Import momentmoment = Moment (APP)
#引入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 ()

  

Python Flask Module

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.