Python__flask初识

1.  debug:在app.run()里面加上app.run(debug=True), 在浏览器中调试的时候可以直接显示出错误.

2.  在url中传递参数,可以这样   

@app.route('/chuancan/<id>')
def my_post(id):
    return '传递的参数为:%s' %id
#一定要在路由里面把传递的参数用尖括号括起来
#url可以这样  http://localhost:5000/chuancan/123

>>>传递的参数为123

3.  根据视图函数来找url地址:

from flask import url_for

@app.route('/host/')
def host():
    pass

print(url_for('host'))

>>>/host/
#url_for里面传入函数名字,反回的是路由地址

4.  跳转/重定向:

from flask import redirect

@app.route('/host/')
def host():
    return redirect('/index/')


>>>访问 http://localhost:5000/host
        如果有index路由,则会跳转到index页面去:
            http://localhost:5000/index

5.  模板:

from flask import render_template

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

>>>把index.html模板文件渲染之后加载出来

6.  模板传参:

from flask import render_template

@app.route('/index/')
def index():
   
    return render_template('index.html',a=1)

#index.html  ->  用{{ a }} 调用

>>> 1

7. jinja2 语句:

#index.html 里面
{
% for foo in session %} {% endfor %} {% if session %} {% endif %} 这样用-.-

8.  jinja2 过滤器,就是函数:

#index.html 里面

{{ something|default('lalala')}}

#如果something这个变量没有,则用default里面的内容替代

{{names|length}}

#如果names是一个列表或者字典一类的,返回它的元素个数

9.  继承模板:

#base.html

<body>
hahaahahahah11111111
{% block main %}{% endblock %}
</body>

#这是一个父模板,如果在子模版中要修改东西,可以加一个block.
#index.html

{% extends 'base.html' %}
{% block main %}
<h1>添加的子东西</h1>
{% endblock %}

#这是个继承了base.html的页面,继承用extends,如果渲染完成之后是这样:


>>>hahaahahahah11111111        ->父模板的
       添加的子东西              ->子模板在block里面加的

10.  链接:

#index.html


<a href="{{url_for(login)}}"></a>

#推荐用url_for(视图函数)

猜你喜欢

转载自www.cnblogs.com/cccy0/p/8993012.html