Flask(鱼书项目)学习笔记(一)——深入了解Flask路由
Flask安装过程略。
判断查询参数是否为isbn号
@app.route("/search/<q>/<page>")
def search(q,page):
"""
搜索书籍路由
:param q: 关键字 OR isbn
:param page: 页码
"""
# isbn isbn13 由13个0-9在数字组成
# isbn10 由10表0-9表数字组组成,中间可能包含' - '
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.isdigit():
isbn_or_key = 'isbn'
pass
知识点:
- 字符串中的**isdigit()**函数可以判断是否为数字
- in关键字判断一个字符串是否在另一份字符串内
- 多个逻辑判断排列原则:
- 有更大可能判断结果为假的条件应该放在前面
- 需要查询数据库的操作由于会消耗资源,应该尽量靠后
代码重构
@app.route("/search/<q>/<page>")
def search(q, page):
"""
搜索书籍路由
:param q: 关键字 OR isbn
:param page: 页码
"""
isbn_or_key = is_isbn_or_key(q)
helper.py
def is_isbn_or_key(word):
"""
判断word是isbn号还是查询关键字key
isbn isbn13 由13个0-9在数字组成
isbn10 由10表0-9表数字组组成,中间可能包含' - '
:param word:
:return: key or isbn
"""
isbn_or_key = 'key'
if len(word) == 13 and word.isdigit():
isbn_or_key = 'isbn'
short_word = word.replace