flask basis python learning

What is the Flask?
The Flask is a Web framework is to provide a tool, library and technology to allow you to build a Web application. The Web application
can be some of the Web page, blog, wiki, Web-based calendar application or business website.
Flask-dependent modules:
web service gateway interface (Python Web Server Gateway Interface, abbreviated as WSGI
Werkzeug WSGI a kit for a python language defined between the web server and web applications or frameworks
kinds of simple and universal excuse, other language has a similar interface)
jinja2 template engine

Flask advantage

Flask belong Micro Framework (micro-framework) in this category, usually small micro-architecture does not rely on external libraries framework
framework is lightweight
depend hours update
focuses on security bug

The first flask procedure

from flask import Flask
app = Flask(__name__)  #导入Flask对象

@app.route('/')    #把修饰的函数注册为路由
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

Variable rules

Give the url add variables section, you can mark these special characters will be passed as a parameter to your function name for this part of <variable_name>

from flask import  Flask
app = Flask(__name__)  #创建对象

@app.route('/')
def hello_world():
    return 'Hello World'

@app.route('/user/<username>')
def show_user_profile(username):
    # 显示该用户名的用户信息
    return 'User %s'  % username

@app.route('/post/<int:post_id>')
def show_post(post_id):
    # 根据ID显示文章,ID是整型数据
    return 'Post %d'  % post_id

if __name__ == '__main__':
    app.run()

The program will run in the browser address modified to http://127.0.0.1:5000/user/ history
is displayed:
flask basis python learning

Construction of url

If the flask can match the url, then you can use url_info () to specify the function to
build url, he receives the function name as the first argument, accept the rules of named parameters corresponding to the url variable part, unknown variable part will be added to the url end as query parameters

from flask import Flask , url_for
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

@app.route('/user/<username>')
def show_user_profile(username):
    # 显示该用户名的用户信息
    return 'User %s' % username

@app.route('/post/<int:post_id>')
def show_post(post_id):
    # 根据ID显示文章,ID是整型数据
    return 'Post %d' % post_id

@app.route('/url/')
def get_url():
    # 根据ID显示文章,ID是整型数据
    return url_for('show_post',post_id=2)

if __name__ == '__main__':
    app.run(debug=True)

Browser to access url:
flask basis python learning

Render Template

When a user accesses the root address of the program, our view of the function to the passenger
-side door return line of HTML code. However, a full HTML pages often require dozens of
lines or even hundreds of lines of code, if you have written a function in view, it is really a nightmare. Such a
code is also simple and is neither difficult to maintain the correct approach is to HTML code is stored in a separate text
member, so that the business logic and presentation logic separate procedures, i.e., the controller and user interface
separation.
In dynamic Web applications, the view function returns HTML data corresponding often need to
dynamically generated variables (such as query parameters). When the HTML code to save a separate file
, we can not re-use string concatenation string formatting or manner in the HTML code
inserted into the variables, then we need to use a template engine (template engine). By mold
plates engine, we can use the special syntax in the HTML file to mark that the variable, such
includes a fixed portion and a dynamic content file called reusable template (template).
The role of the template engine that reads and executes special syntax notation templates, and in accordance pass
into the variable data is replaced with the actual value of the output of the final HTML page. This process is known
as rendering (rendering). Flask default template engine is Jinja2, it is a function
able to complete Python template engine, in addition to setting variables, but also allows us to add in the template if
judgment is performed for iteration, call functions, etc., in various ways to control the output of the template . For
Jinja2, the template can be plain text files in any format, such as HTML, XML,
CSV, LaTeX, etc.

Create templates folder in the file, and then create two files named index.html and user.html then render.py rendering templates

render.py

from flask import  Flask, render_template
app= Flask(__name__)

@app.route('/')
def hello_world():
    return render_template('index.html',name='经验')

@app.route('/user/<username>')
def show_user_profile(username):
    # 显示该用户名的用户信息
    return render_template('user.html', name=username)

if __name__ == '__main__':
    app.run(debug=True)

user.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>hello, {{ name }}!</h1>

</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>hello {{ name }} </h1>

</body>
</html>

Browser:
flask basis python learning
flask basis python learning

Template syntax

Jinja2 engine utilizing such templates, we can put a portion of the program logic die
plate to. Simply put, we can use Python statements and expressions in the template to manipulate
the output data. But note that, Jinja2 does not support all Python syntax. And
for considerations of efficiency and code organization, we should use the appropriate template, and only the output
of a control logic related to the operation into the template.
Jinja2 allows you to use most of the Python object in the template, such as strings, columns,
tables, dictionaries, tuples, integers, floating point, boolean value. It supports basic arithmetic sign
(+, -, *, /, etc.), comparison (! == example, =, etc.), logic symbol (and,
or, and Not parentheses) and in, is, None, and Boolean ( True, False).
Jinja2 provides an output to control a variety of control structures of the template, and wherein if the most commonly used for
both. In Jinja2, the statement uses the {% ...%} identify, in particular, should be noted that, in the language
where the end of the sentence, we must add the closing tag:
{% IF user.bio%}
<i> {{user.bio }} </ I>
{%}% the else
<I> Not Provided This User A has Bio. </ I>
{%} endif%

If in this statement, if user.bio already defined, rendering {% if user.bio%} and
content between {% else%}, otherwise rendering {% else%} and {% endif%} between the default content. End {% endif%} to the end of the statement if the statement, this line can not be omitted.
As in Python and, for a sequence of iteration statement is used:
<UL>
{%} for Movie in Movies%
<Li> movie.name {{}} - {{}} movie.year </ Li>
{% endfor }%
</ UL>

jinja2 template engine

1. What is Jinja2 template engine?

  • Official Website: http://docs.jinkan.org/docs/jinja2/
    Jinja2 is a modern, designer-friendly, modeled on the Python Django template language templates. It's fast, widely used, and offers an optional template sandbox execution environment to ensure safety:
  • . 1) Web development in python, business logic (in essence, the content view function) and logical page (html pieces) apart, so that enhance the readability of the code, the code easier to understand and maintain;
  • 2) rendering template: In the html file through dynamic assignment, will be re-translated html file (template engine into force) to return the process to the user.
  • 3) Other template engine:. Mako, Template, Jinja2

2. Jinja2 grammar

Jinja2 variable display Syntax:

{{Variable name |}} function calls

{{ name }}
{{ url_for() }}
{{ get_flshed_messages() }}

Jinja2 variable built-in filter:

"hello".lower()

safe            渲染值时不转义
capitalize      把值的首字母转换成大写,其他字母转换成小写
lower           把值转换成小写形式
upper           把值转换成大写形式
title           把值中每个单词的首字母都转换成大写
trim            把值的首尾空格去掉
striptags       渲染之前把值中所有的 HTML 标签都删掉

How custom filter?

for loop:

        {% for i in li%}
            xxx
        {% endfor %}

The if statement

        {% if user == 'westos'%}
            xxxx
        {% elif user == 'hello' %}
            xxx
        {% else %}
            xxx
        {% endif%}

Macro operations

  • Equivalent function

    How to define a macro?

        <!--相当于python里面的定义函数, 后面使用的场景: 分页显示-->
        {%  macro render(id) %}
            <h1>hello world {{ id }}</h1>
        {% endmacro %}

How to call a macro?

    <!--调用定义好的宏(类似于python中的函数)-->
    {{ render(1) }}
    {{ render(2) }}
    {{ render(3) }}

include contains the operating

  • How to use: {% include "06_inclued.html"%}

Template inheritance:

And general site navigation bar at the bottom does not change, in order to avoid rewriting navigation information;

  • How to define a template?
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}  {% endblock %}</title>
</head>
<body>
<div style="width: 100px; height: 200px" > 这是导航栏</div>
{% block body %}
hello
{% endblock %}
<div style="width: 100px; height: 200px" >这是底部</div>
</body>
</html>

- 如何继承基模板?

{% extends  '06_base.html'%}
{% block title %}
    继承案例
{% endblock %}
{% block body %}
<span style="color: green">这是最新填的block内容</span>
{% endblockfrom flask  import  Flask, render_template

Example: template inheritance py:

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

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

@app.route('/blog/')
def blog():
    return  render_template('blog.html')
if __name__ == '__main__':
    app.run(port=5002) %}

base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %} {% endblock %}</title>
    <style>
        .nav{
            width: 100%;
            height: 50px;
            border: 1px solid red;
        }
        .left{
            width: 20%;
            border: 1px solid red;
            float: left;
            height: 100px;
        }

        .right{
            width: 79%;
             border: 1px solid green;
            float: left;
            height: 100px;
        }
    </style>
</head>
<body>

<div class="nav">
    导航栏
    <button>登录</button>
    <button>注册</button>
</div>

<div class="left">
    {% include 'left.html' %}

</div>

<div class="right">
    {% block body %}

    {% endblock %}
</div>

</body>
</html>

bbs.html

{% extends 'base.html' %}

{% block title %}

论坛
{% endblock %}
{% block body %}
<h1>bbs</h1>

blog.html

{% extends 'base.html' %}
{% block title %}

博客
{% endblock %}

{% block body %}
<h1>blog</h1>

index.html

{% extends 'base.html' %}

{% block title %}

主页
{% endblock %}
{% block body %}
<h1>index</h1>

left.html

<ul>
    <li>新闻</li>
    <li>财经</li>
    <li>八卦</li>
<url>

Guess you like

Origin blog.51cto.com/13810716/2473591