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)