flask

一、flask
from flask import Flask, jsonify

app = Flask(__name__)
#实例化Flask
if __name__ == '__main__': #执行函数
app.run()


二、定义链接
#http://127.0.0.1:5000/ 
@app.route('/', methods=['GET'])
def home():
return 'hello world!'

#带参
@app.route('/article/<id>', methods=['GET'])
def article(id):
return '%s' % id


#返回json
tasks = [
{
'id': 1,
'title': u'OSPA',
'description': u'This is ospaf-api test',
'done': False
},
{
'id': 2,
'title': u'Garvin',
'description': u'I am garvin',
'done': False
}
]
@app.route('/', methods=['GET'])
def home():
return jsonify({'tasks': tasks})


三、url反转:url_for
@app.route('/', methods=['GET'])
def home():
print url_for('article', id='55')
return jsonify({'tasks': tasks})


@app.route('/article/<id>/', methods=['GET'])
def article(id):
return '%s' % id

四、重定向
return redirect('/login/')
重定向到url:/login/

五、渲染
from flask import render_template
return render_template('index.html')
return render_template('index.html',username=u'晓颖') #传参,前端用{{username}}接收
若是需要传送的参数比较多,可以吧参数写成字典,把字典以一个model传送过去
@app.route('/login/')
def login():
context = {
'username': u'晓颖',
'sex': u'',
'age': 18
}
return render_template('index.html', context=context)

或者使用**吧字典转换为关键字,传送过去
  return render_template('index.html', **context)
 
六、母版 
定义一个母版页Site,在别的网页引用时用下面的代码
{% extends 'Site.html' %}

flock占位符:
母版里面输入:{% block main%}{% endblock %}

    页面输入
{% block main %}
<a>占位符里面的内容</a>
{% endblock %}
七、链接
<a href="http://127.0.0.1:5000/login/">登录</a>
<a href="/login/">登录</a>
<a href="{{url_for('login')}}">登录</a>
引用图片、css、js文件可以采用以下方法
1)建一个static文件夹,会自动渲染,
2)在static文件夹下面新建images、css、js文件夹
3)在各个文件夹下面新建想要引用的文件
  我们用css举例
  

    在页面通过链接引用css

    <link rel="stylesheet" href="{{url_for('static',filename='css/index.css')}}">

    图片,js同理。

 
posted @ 2017-10-30 19:56  wskxy  阅读(158)  评论(0编辑  收藏  举报