python flask 學習與實戰

路由的另外一種表示,在類視圖中會使用

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 ''時無回顯,以下面,訪問這個,會跳轉到百度html

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數字組成python

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()
相關文章
相關標籤/搜索