路由的另一种表示,在类视图中会使用
from flask import Flask, make_response
app = 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_response
app = Flask(__name__)
def hello():
# status code
# content-type(http headers text/html)
headers = {
'content-type':'text/plain',
'location':'http://baidu.com'
}
#response = make_response('<html></html>', 301)
#response.headers = headers
#return response
return '<html></html>', 301, headers
#return "<html></html>"
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 Flask
app = Flask(__name__)
@app.route('/book/search/<q>/<page>')
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'
pass
if __name__ == '__main__':
app.run()