flask作为轻量级的web应用框架
创建一个简单的flask应用
from flask import Flask,url_for,redirect
app = Flask(__name__)
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello():
# pass
return 'Hello World'
@app.route('/user/<username>')
def show_user_profile(username):
# pass
# show the user profile for that user
return redirect('https://www.baidu.com')
return 'User %s' % username
@app.route('/post/<int:post_id>')
def show_post(post_id):
# pass
# show the post with the given id, the id is an integer
return 'Post %d' % post_id
@app.route('/projects/')
def projects():
# pass
return 'The project page'
@app.route('/about')
def about():
# pass
return 'The about page'
# url_for('show_post',post_id=123456)
with app.test_request_context():
print(url_for('about'))
print(url_for('projects'))
print(url_for('show_user_profile', username='Alfie'))
print(url_for('show_post',post_id=123456))
if __name__ == '__main__':
app.run(debug=True)
总结:
@app.route('/post/<int:post_id>')类似这种模式下,可以接受一些<converter:variable_name>
converter | 描述 |
int | 接受整数 |
float | 同 int ,但是接受浮点数 |
path | 和默认的相似,但也接受斜线 |
url_for :获取函数的url地址,可用于构造url,如给一些css文件生成url
debug=True在调试模式不能应用生产环境中,调试模式中在代码修改后可以重新自动载入,方便调试应用
redirect:重定向url地址如:redirect('https://blog.csdn.net/weixin_41341221')可以跳转到其他页面
捕获异常:
在Flask中通过装饰器来实现捕获异常,errorhandler()接收的参数为异常状态码。视图函数的参数,返回的是错误信息。
@app.errorhandler(404)
def error(e):
return '您请求的页面不存在了,请确认后再次访问!%s' % e