即将放弃python的app_Flask从入门到放弃1:路由app.route()

Flask从入门到放弃1:

Flask中的路由app.route():

Flask是基于Werkzeug,Python WSGI实用程序库和Jinja2(Python的模板引擎)的微型框架。

比如:

app = Flask(__name__)

@app.route("/")

def hello():

return "Hello World!"

要理解它,先了解一下装饰器:

举个例子:

# This is our decorator

def simple_decorator(f):

# This is the new function we're going to return

# This function will be used in place of our original definition

def wrapper():

print "Entering Function"

f()

print "Exited Function"

return wrapper

@simple_decorator

def hello():

print "Hello World"

hello()

运行上述代码会输出以下结果:

Entering Function

Hello World

Exited Function

上面是不接受传参的装饰器例子,下面演示一下传参的:

def decorator_factory(enter_message, exit_message):

# We're going to return this decorator

def simple_decorator(f):

def wrapper():

print enter_message

f()

print exit_message

return wrapper

return simple_decorator

@decorator_factory("Start", "End")

def hello():

print "Hello World"

hello()

给我们的输出是:

Start

Hello World

End

重新看一下前面的函数

@app.route("/"):

表示传递一个网站,“/”是网站的主目录,也就是http://127.0.0.1:5000/

假如把"/"改成:'/simon',那么就在网页上输入http://127.0.0.1:5000/simon

形参的规则可以用指定的转换器,比如下面的例子:

@app.route('/post/')

def show_post(post_id):# show the post with the given id, the id is an integer

return 'Post %d' % post_id

转换器有下面几种:

int:

接受整数

float:

同 int ,但是接受浮点数

path:

和默认的相似,但也接受斜线

def hello():

这个是传输给route的函数,里面返回值“Hello World!”就是显示到网页上的内容

假如需要显示html文件:

编写一个html文件,命名为index.html,比如:

Hello World

然后将return返回改成:

return render_template('index.html')

当然,在这之前要先导入 render_template模块

假如要导入CSS样式,编辑CSS文件,比如style.css:

body {

background: red;color: yellow;

}

上述的html也做改动:

Hello World

整个项目的结构如下:

├── app.py

├── static

│   └── style.css

└── templates

└── index.html

我们还可以把导入模板,Flask使用jinja模板

@app.route('/hello/')

def hello(name):

return render_template('page.html', name=name)

最后的return返回一个叫page.html的文件并传递形参name,name正是在URL的一部分数据

新建一个文件叫page.html

Hello {{ name }}!

这里我们忽略html的其他结构

网址输入:http://127.0.0.1:5000/hello/paul

我们就可以看到Hello paul的字样

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值