博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

flask入门

Posted on 2022-12-07 15:07  心默默言  阅读(23)  评论(0编辑  收藏  举报

1.hello word示例

from flask import Flask

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello World!'


if __name__ == '__main__':
    app.run(port='5001')
app.run(host, port, debug, options)

参数 说明 默认值
host 主机名,设置为“0.0.0.0”以使服务器在外部可用 127.0.0.1(localhost)
port 端口号 5000
debug 调试模式,代码更新会自动重启服务,提供一个调试器来跟踪应用程序中的错误 False
options 要转发到底层的Werkzeug服务器的参数

注:pycharm中修改host和port

 

 

2.路由

现代Web框架使用路由技术来帮助用户记住应用程序URL。Flask中的route()装饰器用于将URL绑定到函数,例如:

@app.route('/hello')
def hello_world():
   return 'hello world'

URL /hello 规则绑定到hello_world()函数,如果访问http://localhost:5000/hello,hello_world()函数的输出将在浏览器中呈现。

3.变量规则

通过把 URL 的一部分标记为 <variable_name> 就可以在 URL 中添加变量,标记的部分会作为关键字参数传递给函数。

from flask import Flask
app = Flask(__name__)

@app.route('/hello/<username>')
def hello(username):
    return f'Hello {username}!'

if __name__ == '__main__':
   app.run(debug = True)

在上面的例子中,在浏览器中输入http://localhost:5000/hello/Kint,则Kint将作为参数提供给 hello()函数,即username的值为Kint。在浏览器中的输出如下

Hello Kint!

通过使用 <converter:variable_name> ,可以选择性的加上一个转换器,为变量指定规则。

转换器说明
string (缺省值) 接受任何不包含斜杠的文本
int 接受正整数
float 接受正浮点数
path 类似 string ,但可以包含斜杠
from flask import Flask
from markupsafe import escape

app = Flask(__name__)

@app.route('/hello/<username>')
def hello(username):
    return f'Hello {username}!'

@app.route('/post/<int:post_id>')
def show_post(post_id):
    return f'Post {post_id}'

@app.route('/path/<path:path>')
def show_path(path):
    return f'path {escape(path)}'

if __name__ == '__main__':
    app.run(debug=True)