from flask import Flask,Response,jsonify #Flask = werkzeug(处理网络的) + sqlalchemy(处理数据库的) + jinja2 (处理模板的) app = Flask(__name__) #讲视图函数中返回的字典,转换成json对象,然后返回 #restful-api class JSONResponse(Response): @classmethod def force_type(cls, response, environ=None): ''' 这个方法只有视图函数返回非字符、非元祖、非Response对象才会调用 :param response:是视图函数的返回值 :param environ: :return: ''' print(response) print(type(response)) if isinstance(response,(list,dict)): #jsonify除了将字典转换成json对象,还将对象包装成了一个Response对象 response = jsonify(response) return super(JSONResponse,cls).force_type(response,environ) #python 面向对象的一个知识点 super app.response_class = JSONResponse @app.route('/') def helloworld(): return 'helloworld'#相当于 return Response(response='hello world',status=200,mimetype='text/html') #直接返回字符串不是更好吗 #为什么还要用Response返回字符串 #因为在某些场合要set_cookie的时候,就要在返回的相应中设置 @app.route('/show/') def shop(): rep = Response('购买成功') rep.set_cookie('商品',value='小米手机,iPad') return rep @app.route('/list/') def list0(): return Response(response='list',status=200,mimetype='text/html') @app.route('/list1/') def list1(): return 'list1',200 #这里相当于一个元祖 @app.route('/list2/') def list2(): return ['1','2','3'] if __name__ == '__main__': app.run(debug=True)
python中反射
反射:可以用字符串的方式去访问对象的属性,调用对象的方法(但是不能去访问方法),python中一切皆对象,都可以使用反射。 反射有四种方法: hasattr:hasattr(object,name)判断一个对象是否有name属性或者name方法。有就返回True,没有就返回False getattr:获取对象的属性或者方法,如果存在则打印出来。hasattr和getattr配套使用 需要注意的是,如果返回的是对象的方法,返回出来的是对象的内存地址,如果需要运行这个方法,可以在后面添加一对() setattr:给对象的属性赋值,若属性不存在,先创建后赋值 delattr:删除该对象指定的一个属性 # 什么是反射?可以用字符串的方式去访问对象的属性 class Test(): _name = "sss" def fun(self): return "Helloword" t = Test() # print(hasattr(t,"_name")) #hasattr(obj,name)#查看类里面有没有name属性 # print(hasattr(t,"fun")) #True if hasattr(t,"_name"): print(getattr(t,"_name")) #sss if hasattr(t,"fun"): print(getattr(t,"fun")()) #Helloword if not hasattr(t,"age"): #如果属性不存在 print("没有该属性和方法,我来给设置一个") setattr(t,"age","18") #给t对象设置一个默认值,默认age=18 print(getattr(t,"age"))
getattr的详细使用:
class Func:
name = 'xiaowu'
def func(self):
print('hello world')
value = getattr(Func,'func') #类里面的属性,或类里的方法,在内存中的地址
value() #相当于 value = Func.func 后面加个括号就是调用它,
print(value)