Flask从入门到放弃1:路由app.route()

Flask从入门到放弃1:css

Flask中的路由app.route():html

参考来源:http://python.jobbole.com/80956/python

   https://www.raspberrypi.org/learning/python-web-server-with-flask/worksheet/web

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

好比:app

app = Flask(__name__)框架

@app.route("/")函数

def hello():post

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/<int:post_id>')
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,好比:

<html>

<body>

<h2>Hello World</h2>

</body>

</html>

而后将return返回改为:

return render_template('index.html')

固然,在这以前要先导入 render_template模块

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

body {
background: red;color: yellow;
}

上述的html也作改动:

<html>

<head>

<link rel="stylesheet" href='/static/style.css' />

</head>

<body>

<h2>Hello World</h2>

</body>

</html>

整个项目的结构以下:

├── app.py ├── static │   └── style.css └── templates └── index.html

咱们还能够把导入模板,Flask使用jinja模板

@app.route('/hello/<name>')

    def hello(name):

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

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

新建一个文件叫page.html

<h1>Hello {{ name }}!</h1>

这里咱们忽略html的其余结构

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

咱们就能够看到Hello paul的字样

相关文章
相关标签/搜索