flask

1、flask
from flask import Flask, jsonify

app = Flask(__name__)
#實例化Flask
if __name__ == '__main__': #執行函數
app.run()


2、定義連接
#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})


3、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

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

5、渲染
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)
 
6、母版 
定義一個母版頁Site,在別的網頁引用時用下面的代碼
{% extends 'Site.html' %}

flock佔位符:
母版裏面輸入:{% block main%}{% endblock %}

    頁面輸入
{% block main %}
<a>佔位符裏面的內容</a>
{% endblock %}
7、連接
<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舉例
  

    在頁面經過連接引用csscss

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

    圖片,js同理。前端

相關文章
相關標籤/搜索