Flask创建app对象及其相关参数等相关知识介绍(二)

一、初始化参数(Flask(参数在以下标识))

  • import_name:导入路径(寻找静态文件目录与模板目录位置的参数)
  • static_url_path:静态文件的地址,默认为’static’
  • static_folder:静态文件的目录,默认为’static’
  • template_folder:模板文件的目录,默认’templates’
  • name:表示当前模块的名字,模块名

二、配置参数(有3种方式)

1、使用配置文件(将配置文件添加到根目录下,例:命名为config.cfg)
app.config.from_pyfile("config.cfg")

注意(在config.cfg文件中,例如只写调试模式,大写):

DEBUG = True
2、使用对象配置参数(写类,使用比较多)
class Config(object):
    DEBUG = True

app.config.from_object(Config)
3、直接操作config的字典对象
app.config['DEBUG'] = True

三、读取配置参数(以配置参数第二种方法来获取,有2种方式)

1、直接从全局对象app的config字典中获取
class Config(object):
    DEBUG = True
    BASE = "大傻逼"

app.config.from_object(Config)

@app.route('/')
def hello_world():
    print(app.config['BASE'])
    print(app.config.get('BASE'))
    return 'Hello World!'
2、通过current_app获取参数
class Config(object):
    DEBUG = True
    BASE = "大傻逼"

app.config.from_object(Config)
@app.route('/')
def hello_world():
    print(current_app.config.get('BASE'))
    return 'Hello World!'

四、将对应函数名字的访问路径地址打印出来的函数

from flask import Flask, url_for, render_template, redirect, request, session, current_app
#1、将对应函数名字的访问路径地址打印出来
 with app.test_request_context():
    print(url_for('user_name', username='大哥'))

五、app.run()中的参数

 app.run(host='0.0.0.0', port=5000)
发布了21 篇原创文章 · 获赞 0 · 访问量 134

猜你喜欢

转载自blog.csdn.net/qq_41706810/article/details/105737792
今日推荐