路由的另一种表示,在类视图中会使用
from flask import Flask, make_responseapp = Flask(__name__)def hello(): return "Hello World!"app.add_url_rule('/hello', view_func = hello)if __name__ == '__main__': app.run(debug=True)
视图函数与普通函数的区别
这里是返回 status code, content-type(在headers中默认是text/html),所以当return ''时无回显,如下面,访问这个,会跳转到百度
from flask import Flask, make_responseapp = Flask(__name__)def hello(): # status code # content-type(http headers text/html) headers = { 'content-type':'text/plain', 'location':'http://baidu.com' } #response = make_response('', 301) #response.headers = headers #return response return '', 301, headers #return ""def helloo(): return "Hello World!"app.add_url_rule('/hello', view_func = hello)if __name__ == '__main__': app.run(debug=True)
实战
编写一个书籍搜索,我这里先实现搜索分类,书籍搜索含关键字和isbn编号搜索,isbn分为isbn10 isbn13 前者有'-',0-9组成,后面有0-9数字组成
from flask import Flaskapp = Flask(__name__)@app.route('/book/search//')def search(q, page): """ q (isbn13 0-9 isbn10'-') page """ isbn_or_key = 'key' if len(q) == 13 and q.isdigit(): isbn_or_key = 'isbn' short_q = q.replace('-', '') if '-' in q and len(short_q) == 10 and short_q.isdgit: isbn_or_key = 'isbn' passif __name__ == '__main__': app.run()