注入 (Injection)
接下來我們看怎麼讓模板引擎該怎麼注入
render_template_string()
使用了"%s"來替換字串{{ }}
裡面的內容作解析,{{ 7+7 }}
時,就會被解析成 14
from flask import Flask, render_template, request, render_template_string
app = Flask(__name__)
@app.route('/',methods=['GET'])
def index():
name = request.args.get('name', 'roy')
template = '''
<div class="center-content error">
<h1>Hello</h1>
<h3>{}</h3>
</div>
'''.format(name)
return render_template_string(template)
if __name__ == '__main__':
app.run(debug=True)
python
的Flask/Jinja2
作為示範
dir()
可查詢物件全部屬性
dir(str)
, dir(list)
...
dir()
,執行結果就會用最大限度的範圍,列出變數、方法和屬性
__builtins__
他儲存了python的內建函數,當python的interpreter被打開(也就是你再terminal或cmd打python3),自動會import進來的內建函數
也就是為甚麼有些type或function我們可以直接打在interpreter裡,不須從外部import進來
我們可以透過 __builtins__
配上__dict__
來使用其他function
__builtins__.__dict__['exec']("print('ok')")
__builtins__.__dict__['__import__']('os').system('whoami')
__class__
class A():
pass
a = A()
print(a.__class__) #<class '__main__.A'>
__mro__
class A:
pass
class B(A):
pass
class C(A):
pass
class D(B, C):
pass
print(D.__mro__) #(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)
__subclasses__
class A(object):
pass
class B(A):
pass
class C(A):
pass
print(A.__subclasses__()) #[<class '__main__.B'>, <class '__main__.C'>]
__bases__
class A(object):
pass
class B(object):
pass
class C(A,B):
pass
print(C.__bases__)
__init__
class A:
def __init__(self):
print('ok')
a = A() # print ok
__globals__
class A(object):
def __init__(self, a, b):
self.a = a
self.b = b
a.__init__.__globals__
# {'A': <class '__main__.A'>, 'a': <__main__.A object at 0x0000000001692390>, 'importlib': <module 'importlib' from 'D:\anaconda\lib\importlib\__init__.pyc'>, '__builtins__': <module '__builtin__' (built-in)>, 'pattern': <_sre.SRE_Pattern object at 0x0000000001695030>, 'base64': <module 'base64' from 'D:\anaconda\lib\base64.pyc'>, 'sys': <module 'sys' (built-in)>, 'flag': <module 'os' from 'D:\anaconda\lib\os.pyc'>, '__package__': None, 'os': <module 'os' from 'D:\anaconda\lib\os.pyc'>, '__doc__': None, 'match': <_sre.SRE_Match object at 0x00000000039A9B28>}
__getattribute__
, __getattr__
__getattribute__
__getattribute__
,不管該個data member是否存在class A:
def __init__(self):
self.name = "Bob"
def __getattribute__(self,item):
print("ok")
a = A()
a.name # ok
a.age # ok
__getattr__
__getattr__
class A:
def __init__(self):
self.name = "Bob"
def __getattr__(self,item):
print("No attribute")
a = A()
a.age # No attribute
今天先到這,東西有點多