flask学习笔记(一)

1.第一个flask程序

#从flask这个框架中导入Flask这个类
from flask import Flask
#初始化Flask对象。传递参数(__name__)
app = Flask(__name__)

#@app.route是一个装饰器,@开头,且在函数上为装饰器
#这个装饰器作用是做url与视图函数的映射

@app.route('/')
def index():
    """Video streaming home page."""
    return render_template('index.html')


#如果这个文件是作为入口程序运行,那么运行app.run
if __name__ == '__main__':
    #启动一个用户服务器来接受用户请求
    #whihe true
    app.run()

2.debug模式

在上述代码app.run()括号内jian键入debug=True,及配置完成debug模式

3,使用配置文件config

a,在templates文件夹下新建文件config.py

b,在主app文件中导入config.py代码如下:

import config

app.config.from_object(config)

c,后期其他参数也是放在这个配置文件中,如‘SECRET_KEY’,‘SQLALCHEMY’,这些都与数据库有关

4,url传参到视图函数

a,参数左右:在相同的url中,加载不同的参数获取不同的数据

b,代码演示:

from flask import Flask,config
app=Flask(__name__)
app.config.from_object(config)
@app.route('/')
def hello_world():
    return 'hel0lo wrd!'

@app.route('/arctle/<id>')
def arctle(id):
    return u'您请求的参数是:%s' %id



app.run()

结果如图:

c,

注:参数(id)放在两个尖括号中,视图函数中放与url函数同名的参数。

5,从视图函数反转得到url

a,反转url:已知视图函数,打印url。

b,代码演示

def index():

    print (url_for('my_list'))
    print (url_for('arctle',id='123'))
    return 'hel0lo wrd!'

@app.route('/list')
def my_list():
    return 'list'

@app.route('/arctle/<id>')
def arctle(id):
    return u'您请求的参数是:%s' %id

c,结果显示

d:应用:页面重定向、模板中超链接。

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

猜你喜欢

转载自blog.csdn.net/Terry_n/article/details/81111453