python flask 基础学习(1)

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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值