装饰器
装饰器就是想给现有的模块加上一些小装饰(一些小功能,这些小功能可能好多模块都会用到),但又不让这个小装饰(小功能)侵入到原有的模块中的代码里去
参考:
1. [廖雪峰的python教程中装饰器部分][1]
2. [Python装饰器学习(九步入门)][2]
简单用法
def doSomeThing(func):
def wrapper():
print 'call func() before...'
return func()
return wrapper
@doSomeThing
def hello():
print 'hello world'
if __name__ == '__main__':
hello()
#----->
#call func() before...
#hello world
具体解析
带装饰器hello()
#call func() before...
#hello world
#不带装饰器的hello--->实现装饰器效果
doSomeThing(hello)()
#hello world
这个就是把函数名称当作参数和返回值,在内部调用,控制调用前后的操作逻辑
Flask
安装
`pip install flask`
运行
一个最简易的网页
#-*- encoding=UTF-8 -*-
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'hello'
if __name__ == '__main__':
app.run(debug=True)
至此,一个简单的网页就运行起来了,下面就是针对这个网站进行一些细节操作,逐步完善
多映射
"""
可以同时接受多个路径的映射,只要在上面添加装饰器好了,避免因后期升级导致旧的连接无法使用
"""
@app.route('/') #指定根路径的回调
@app.route('/index/')
def index():
return 'hello'
参数变量
""" 通过url传递参数 """
@app.route('/profile/<uid>/')
def profile(uid):
return 'profile : ' + uid
""" 指定传递参数的类型,如果传递的参数类型不符合,会直接回404 """
@app.route('/profileInt/<int:uid>/')
def profileInt(uid):
return 'profileInt : ' + str(uid)
模板
使用模板需要导入render_template
并且要在主程序所在目录下创建templates文件夹,然后把模板文件放到这里面
我这里的模板文件是profile.html
<html>
<body>
{# 这个是Jinja2模板语法,这个是注释 #}
uid={{uid}}<br> {# 这是获取变量 #}
{% for i in range(0,5): %}
{{loop.index}}, number:{{i}}<br>
{% endfor %}
{# 可以理解定义了一个带参数的宏 #}
{% macro render_color(color) %}
<div>This is color {{color}}</div> {{caller()}}
{% endmacro %}
{% for color in colors: %}
<br>
{% call render_color(color) %} {# 调用 #}
render_color_demo<br>
{% endcall %}
{% endfor %}
</body>
</html>
#-*- encoding=UTF-8 -*-
from flask import Flask, render_template #导入模块
app = Flask(__name__) #创建对象
@app.route('/') #指定根路径的回调
@app.route('/index/')
def index():
return 'hello'
@app.route('/profile/<uid>/')
def profile(uid):
#return 'profile : ' + uid
colors = ('blue', 'red', 'green')
return render_template('profile.html', uid=uid, colors=colors)
@app.route('/profileInt/<int:uid>/')
def profileInt(uid):
return 'profileInt : ' + str(uid)
if __name__ == '__main__':
app.run(debug=True) # debug,开启debug模式
404模板
404的模板是no_found.html, 也要放在templates里面
添加request模块,获取当前请求的url
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Not Found</title>
</head>
<body>
{{request}}
</body>
</html>
from flask import Flask, render_template, request
@app.errorhandler(404)
def not_found(error):
return render_template('not_found.html', request=request.url)
重定向
重定向就是将网页自动转向重定向,即:301永久性重定向和302临时性重定向。实施301后,新网址完全继承旧网址,旧网址的排名等完全清零;实施302后,对旧网址没有影响,但新网址不会有排名
from flask import Flask, render_template, request, redirect
@app.route('/newpath')
def newpath():
return 'newpath'
@app.route('/redirct/<int:number>')
def redirctPage(number):
return redirect('/newpath',code=number)