【flask-进阶1】

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010859970/article/details/79920051

工具:postman

2.6最小原型与唯一URL原则
在flask中视图函数等价于MVC中的control
基于类的视图(即插视图)
路由的时候将不带’/’的地址重定向为带’/’的地址
(1)
@app.route(‘/hello’)
def fun():
pass
如果访问的地址为’localhost:5000/hello’,此时可以访问到
如果地址为’localhost:5000/hello/’,此时是访问不到的

(2)
@app.route(‘/hello/’)
def fun():
pass
这个时候无论后面带不带’/’,都是会访问到的

2.7路由的另一种注册方法
(1)装饰器
@app.route(‘/hello/’)
def hello():
return ‘hello, flask!’
(2)add_url_rule
app.add_url_rule(‘/hello’, view_func=hello)
这时候的view_func=hello中的hello就是hello这个函数
什么时候需要用add_url_rule?
在基于类的视图(即插视图)的时候

2.8 config参数

2.9 理解main
if name == ‘main‘:
在生产环境中,nginx+uwsgi
项目不会是python manage.py这样去启动的,一般会将manage.py作为uwsgi的一个模块去启动
当碰到if的这条判断的时候,就不会再去启动flask自带的那个服务器了

2.10 response
会返回一些附加信息
status 比如code 200,404,301
content-type 比如http headers
content-type是用来告诉浏览器如何解析返回的这段文本
如果不指定content-type,则flask会指定其为一个默认值为text/html
视图函数中返回的是Response对象

创建response对象的方法:
headers = {
‘content-type’:’text/plain’,
‘location’:’http://www.bing.com‘# 可以重定向

}
response=make_response(‘‘, 404)
response.headers = headers

content-type的返回有以下几种:
‘application/json’
‘text/html’
‘text/plain’

或者不用response:用元组的方式
return ‘,301, headers

3.1
3.2数据搜索与查询 数据API
API
https://api.douban.com/v2/book
http://t.yushu.im/v2/book/isbn/{isbn}
http://t.yushu.im/v2/book/search?q={}&start={}&count{}

3.3书籍搜索与查询 搜索关键字
调用外部API来实现
重构前:
@app.route(‘/book/search//’)
def search(q, page):
“””
q:普通关键字和ISBN
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 amd short_q.isdigit():
isbn_or_key = ‘isbn’

对代码重构以后:
def is_isbn_or_key(q):
# 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 amd short_q.isdigit():
isbn_or_key = ‘isbn’
return isbn_or_key

@app.route(‘/book/search//’)
def search(q, page):
“””
q:普通关键字和ISBN
page
“””
is_isbn_or_key(q)

3.5调用API
urllib
requests

from urllib import request
import requests # 推荐
class HTTP:
def get(self, url, return_json=True):
r = requests.get(url)
# RESTful
# return_json来控制是否返回json格式
# 简洁的写法
# 提倡一般只返回一次return(参考 代码大全)
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 ”

3.6 requests vs urllib

@staticmethod
def get_with_request(url, json_return=True):
url= quote(url, safe=’/:?&’) # 处理中文字符
try:
with request.urlopen(url) as r:
result_str = r.read()
result_str = str(result_str, encoding=’utf8’)
if json_return:
return json.loads(result_str)
except OSError as e:
# 最好不要跑出异常
print(e.reason)
if(json_return):
return {}
else:
return None

3.5节中的get方法实际上是一个静态方法,因为没有用到self,因此可以改为静态方法
class HTTP:
@staticmethod
def get(url, return_json=True):
r = requests.get(url)
# RESTful
# return_json来控制是否返回json格式
if r.status_code != 200:
return {} if return_json else ”
return r.json() if return_json else r.text()
py2
经典类:不继承(object)
新式类:继承(object)

py3
都是新式类:继承(object)

猜你喜欢

转载自blog.csdn.net/u010859970/article/details/79920051