flask-Data and routing

Source: Internet
Author: User
Data

Address of the library database

# 基地址http://t.yushu.im# 关键字搜索http://t.yushu.im/v2/book/search?q={}&start={}&count={}# isbn搜索http://t.yushu.im/v2/book/search/isbn/{isbn}# 豆瓣apiapi.douban.com/v2/book/1003078
Search keywords
    1. According to the above address can know that there are two ways to search, and for the ISBN search, divided into two isbn13 由13个0-9在数字组成 , isbn10 由10表0-9表数字组组成,中间可能包含' - ' , so separate to judge
    2. Note in the function: isdigit() you can tell if it's a number, replace() replace it,
@app.route("/search/<q>/<page>")def search(q,page):    """    搜索书籍路由    :param q: 关键字 OR isbn    :param page: 页码    """    isbn_or_key = 'key'    # 1. 判断长度是否为13且是否为数字    if len(q) == 13 and q.isdigit():        isbn_or_key = 'isbn'    # 2. 把-替换掉,判断是否为纯数字    short_q = q.replace('-', '')    if '-' in q and len(short_q) == 10 and short_q.isdigit():        isbn_or_key = 'isbn'    pass
    1. Multi-logical judgment, you should look at the results as false put to the front, the database operation to the back, so as to save resources
Simple refactoring
    1. The above code is written in the view so inappropriate, not reflect the encapsulation, look bad, should be an implementation of the function encapsulated, set up a function to facilitate future management
    2. In the directory to create a helper.py file, this file is mainly to provide some methods, put the above content here, only need to return a value to be able to
# -*- coding: utf-8 -*-def is_isbn_or_key(word):    isbn_or_key = 'key'    if len(word) == 13 and word.isdigit():        isbn_or_key = 'isbn'    short_word = word.replace('-', '')    if '-' in word and len(short_word) == 10 and short_word.isdigit():        isbn_or_key = 'isbn'    return isbn_or_key
    1. Call this method in the main file, remember to pass the value, and receive the value returned
# -*- coding: utf-8 -*-from flask import Flask,make_response# 1. 这里要导入from helper import is_isbn_or_keyapp = Flask(__name__)app.config.from_object('config')@app.route('/book/search/<q>/<page>')def search(q,page):    # 2. 调用方法即可    is_or_key = is_isbn_or_key(q)    passif __name__ == '__main__':    app.rundebug=app.config['DEBUG'])
Requests request
    1. Because this project is going to visit different URLs, create a new file in the directory http.py , specifically to provide access to the URL
    2. The requests used here, to install first, note: The code must be concise when writing, do not use the Python keyword, so as not to conflict with the Python module and cause this error , the class name HTTP changed to another name
# -*- coding: utf-8 -*-import requestsclass aaa:    # 传入url和是否返回的是json数据,这里是静态方法    @staticmethod    def get(url,return_json=True):        # 发送get请求        r = requests.get(url)        # 因为有的url返回的json数据,但是有的并不是,所以加一个判断,不是的话返回文本        # 还要判断状态码,200的话就是访问成功有数据        if r.status_code != 200:            return {} if return_json else ''        return r.json() if return_json else r.text        # 下面的写法太low        # if r.status_code == 200:        #     if return_json:        #         return r.json()        #     else:        #         return r.text        # else:        #     if return_json:        #         return {}        #     else:        #         return ''
Getting data from the API
    1. First define a class in the directory that is used to get the data, ShanqiuBook
# -*- coding: utf-8 -*-from http import aaaclass ShanqiuBook:    isbn_url = 'http://t.yushu.im/v2/book/search/isbn/{}'    keyword_url = 'http://t.yushu.im/v2/book/search?q={}&count={}&start={}'    # 根据isbn进行搜索,这里使用这个静态装饰器,调用类变量更加的方便    @classmethod    def search_by_isbn(cls,isbn):        # 调用类变量,        url = cls.isbn_url.format(isbn)        # 调用上面的方法用于请求网址        result = aaa.get(url)        # 这里返回的是json数据,但是在py中就是字典了        return result    # 根据关键字进行搜索    @classmethod    def search_by_keyword(cls,keyword,count=15,start=0):        url = cls.keyword_url.format(keyword,count,start)        result = aaa.get(url)        return result
    1. Then get the returned data in the view
# -*- coding: utf-8 -*-from flask import Flaskfrom helper import is_isbn_or_keyfrom flask import jsonify# 实例化from shanqiu_book import ShanQiuBookapp = Flask(__name__)# 载入这个配置文件app.config.from_object('config')@app.route('/book/search/<q>/<page>')def search(q,page):     is_or_key = is_isbn_or_key(q)     if is_or_key == 'isbn':         # 这里直接使用使用类名调用就可以         result = ShanQiuBook.search_by_isbn(q)    else:         result = ShanQiuBook.search_by_keyword(q)        # 因为返回的是json数据,要手动的进行解析,这样写的话非常麻烦    # return json.dumps(result), 200, {'content-type': 'application/json'}    # 这里使用flask自带的jsonify替换麻烦的json.dumps和元组     return jsonify(result)    if __name__ == '__main__':    app.run(debug=app.config['DEBUG'])
Splitting a view function into a separate file
    1. If the view function is written in the main file, it is not conducive to maintenance, but should put them into a file, each module is an attempt to use the direct reference, so as to facilitate maintenance
    2. Create a App/web folder under the root directory, create a book.py file under this folder, specifically for storing the book module, and then referencing the module in the main file.book.py
# -*- coding: utf-8 -*-from flask import jsonifyfrom helper import is_isbn_keyfrom ShanqiuBook import ShanqiuBook# 为了让book.py模块可以使用app对象from demo import app@app.route('/book/search/<q>/<page>')def hello(q,page):    # 调用方法判断用户是根据什么查的    is_or_key = is_isbn_key(q)    if is_or_key == 'isbn':        result = ShanqiuBook.search_by_isbn(q)    else:        result = ShanqiuBook.search_by_keyword(q)    return jsonify(result)
    1. In the main file at this time
# -*- coding: utf-8 -*-from flask import Flask# 为了可以注册book.py中的路由from app.web import bookapp = Flask(__name__)app.config.from_object('config')if __name__ == '__main__':    app.run(debug=app.config['DEBUG'])
    1. But in this case, there will be 404, because there is a circular reference
Cycle Introduction Process Analysis
    1. Because the app is initialized two times throughout the process,
    2. Throughout the process, two core app objects have been initialized, and the registered route is registered with the app initialized in the blue process. But the start-up service is launched by the app in the red process
    3. The App object used to register the route in book is the App object (in the blue process) in which he imports the Fisher module, rather than the app object that is instantiated in the red main process
    4. Question 1: Because all is introduced by Fisher to book, one module will only introduce another module at a time, so it only executes once.
    5. Issue 2: Because one is the main process to execute the Fisher file; Once the book module is imported into Fisher
    6. In order to verify our conclusion, we instantiate in the app, start, register where the route is to join the log information,
print("id为"+str(id(app))+"的app注册路由")@app.route("/book/search/<q>/<page>")def search(q, page):    isbn_or_key = is_isbn_or_key(q)    if isbn_or_key == 'isbn':        result = YuShuBook.search_by_isbn(q)    else:        result = YuShuBook.search_by_key(q)    return jsonify(result)
    1. Master File
app = Flask(__name__)print("id为"+str(id(app))+"的app实例化")app.config.from_object("config")# 为了可以注册book.py中的路由from app.web import bookif __name__ == '__main__':    print("id为" + str(id(app)) + "的app启动")    app.run(debug=app.config['DEBUG'])
    1. The results are as follows
id为92323280的app实例化id为107142192的app实例化id为107142192的app注册路由id为92323280的app启动

You can see the app registered for routing, and the app that started the service is not the same app. And the last app that was launched was the app that was first instantiated, the red main process app, and the app that registered the route was a post-instanced app, which is the blue process of importing the Fisher module from book

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.