DAY2-Flask项目

回顾:

1.安装pipenv虚拟运行环境,隔离项目 (启动:pipenv shell)

2.安装flask(pipenv install shell),查看项目依赖(pipenv graph)

3.查看项目名虚拟环境安装目录:pipenv --venv

 

项目编写:

1.最小的原型:

from flask import Flask

app = Flask('__name__')

app.run()

2.视图函数:路由(route修饰器)注册 + 函数

@app.route('/hello')
def hello():
return 'Hello!'

 

3.开启调试模式:

app.run(debug=True)

 

4.路由另一种注册方式:

上一中使用了修饰器

通过flask核心对象注册:

app.add_url_rule('/hello', view_func=hello)

两个参数:URL和视图函数

 

5.接受外网访问和端口

app.run(host='0.0.0.0', port=80)

 

6.配置文件:当项目发布到生产环境是debug要关闭,开发环境和生产环境要是镜像关系(一模一样),方法是使用配置文件

创建:config.py:

DEBUG = True

导入配置文件:

1.当做模块导入:from config import DEBUG

2.app方法导入:app.config.from_object('config') # 导入载入配置文件 参数为模块路径

(# 如果通过from_object方式载入配置文件,要求参数全大写!# DEBUG默认值为False,所以要覆盖config中的参数,DEBUG也必须大写)

读取配置文件:

app.run(host='0.0.0.0', debug=app.config['DEBUG'])

 

7.if判断:

在项目中Fisher文件是入口文件,其中app.run()只能在入口文件中执行其他模块(即使入口文件被导入)不允许执行,就需要if加以限制

 

if __name__ == '__main__': #确保if里面的语句只在入口文件里执行
#保证在生产环境中(nginx + uwsgi)不会再一次启动web服务器,因为uwsgi已经启动了服务器

 

 

8.Response:

视图函数除了返回字符串还会返回:

1.status状态码  2.content type(在http header标签中):告诉接受方如何解析文本,不修改默认为text/html

 

Flask会把视图函数返回的字符串当做主体内容,把statuscontent type等一起封装为一个Response对象

创建Response对象:response = make_response()

 

9.第一个API:图书搜索 q:关键字

@app.route('/book/search/<q>/<page>')
def search(q, page):
    isbn_or_key = 'key'  # 默认设为key
    if len(q) == 13 and q.isdigit:  # 字符串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

把上述判断代码封装为一个模块(helper.py)关键字处理

def is_isbn_or_key(word):
    """
    word:普通关键字搜索
    page
    """
    isbn_or_key = 'key'  # 默认设为key
    if len(word) == 13 and word.isdigit:  # 字符串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

在Fisher函数中调用:在视图函数中逻辑判断代码最好封装

from flask import Flask
from helper import is_isbn_or_key
from config import DEBUG
app = Flask(__name__)

@app.route('/hello')
def hello():
    return 'Hello!'

@app.route('/book/search/<q>/<page>')
def search(q, page):
    isbn_or_key = is_isbn_or_key(q)
    pass
# app.add_url_rule('/hello', view_func=hello)

app.run(debug=True)

 

10.访问API:

发送http请求,在文件中封装(http.py):

发送http请求有两种方法:

1. urllib: 自带的模块

2.requests 第三方库处理http请求:

安装requests:1.启动环境pipenv shell  2.安装:pipenv install requests

http.py  : 发送请求并接受结果(json)

import requests

class HTTP:
    @staticmethod  #静态修饰器
    def get(url, return_json=True):
        r = requests.get(url)
        if r.status_code != 200:
            return {} if return_json else ''
        return r.json() if return_json else r.text
为简化的代码:
# if r.status_code == 200:
# if return_json:
# return r.json()
# else:
# return r.text
# else:
# if return_json:
# return {}
# else:
# return ''

 把请求的过程封装为一个类(yushu_book.py):

from http import HTTP
class YuShuBook:
    isbn_url = 'http://t.yushu.im/v2/book/isbn/{}'
    keyword_url = 'http://t.yushu.im/v2/book/search?q={}&count={}&start={}'

    @classmethod
    def search_by_isbn(cls, isbn):
        url = cls.isbn_url.format(isbn)
        result = HTTP.get(url)
        return result
    @classmethod
    def search_by_keyword(cls, keyword, count=15, start=0):
        url = cls.keyword_url.format(keyword, count, start)
        result = HTTP.get(url)
        return result

 

 

  

 

posted @ 2018-06-05 14:33  asamm  阅读(123)  评论(0编辑  收藏  举报