Flask框架(一)

2020-01-16 17:38:08 浏览数 (1)

代码语言:javascript复制
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return '<h1>hello world</h1>'

app.run()

在run()中添加配置

debug  是否调试,修改后自动重启, 可以动态调试

threaded  是否多线程

post  端口

host  主机

插件、扩展库

1.下载,安装

2.初始化配置

flask-script

代码语言:javascript复制
from flask import Flask
from flask_script import Manager


app = Flask(__name__)

manager = Manager(app=app)


@app.route('/')
def index():
    a = 10
    b = 0
    c = a/10
    return '<h1>hello world</h1>'


if __name__=='__main__':
    # app.run(debug=True, port=8000, host='0.0.0.0')
    manager.run()

直接运行没有效果,需要输入参数

代码语言:javascript复制
(venv) D:python3_Flask>python hello.py runserver

 * Serving Flask app "hello" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL C to quit)

多个各种参数

代码语言:javascript复制
(venv) D:python3_Flask>python hello.py runserver -d -r -h 0.0.0.0 -p 8000

 * Serving Flask app "hello" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 184-573-979
 * Running on http://0.0.0.0:8000/ (Press CTRL C to quit)

Flask路由参数

代码语言:javascript复制
@app.route('/params/<ni>/')
def params(ni):
    return '获取参数'    ni

@app.route('/get/<string:name>/')
def get_name(name):
    return '获取name'   name
    
@app.route('/get_age/<int:age>/')
def get_age(age):
    return age

#会将斜线认为是字符    
@app.route('/get_path/<path:Path>/')
def get_path(Path):
    return Path

@app.route('/get_uuid/<uuid:id>/')
def get_uuid(id):
    return id.uuid64()

#从列出的元组中的任意一个
@app.route('/get_any/<any(c, d, e):any>/')
def get_any(any):
    return any

请求方法

代码语言:javascript复制
@app.route('/get_any/<any(c, d, e):any>/', methods = ['GET', 'POST'])
def get_any(any):
    return any

 反向解析

代码语言:javascript复制
@app.route('/url')
def url():

    print(url_for('get_any', any='c'))
    return '反向解析'

0 人点赞