python项目如何读取配置文件(配置端口号,ip等等)

python 复制代码
# -*- coding: utf-8 -*-

import configparser
from flask import Flask, request, jsonify
from BFS import change_dp

# 实例化Flask对象
app = Flask(__name__)


# 读取配置文件
config = configparser.ConfigParser()
config.read('config.ini')


#下面代码省略

if __name__ == '__main__':
    # 启动程序,监听用户请求
    # 一旦请求到来,执行 app.__call__方法
    # 封装用户请求
    # 进行路由匹配
    # 从配置文件中读取端口号和调试模式
    host = config.get('server', 'host')
    port = config.getint('server', 'port')
    debug = config.getboolean('server', 'debug')

    # 启动应用
    app.run(host=host, port=port, debug=debug)

然后在文件夹内新建一个config.ini

python 复制代码
[server]
host = 0.0.0.0
port = 8084
debug = True

这样就能将配置和代码分离

项目结构如下

相关推荐
梦想的旅途21 天前
Python实现企业微信文本消息发送
开发语言·python·企业微信
%471 天前
DAY41
pytorch·python
敲代码还房贷1 天前
VMware17 + Ubuntu22.04 共享 完整步骤
linux·python·ubuntu
大鹏说大话1 天前
美业微信会员系统哪个好
开发语言
测试19981 天前
Selenium 无法定位元素的几种解决方案
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
半亩码田1 天前
C#转Python第3.6篇:Python 的 @property 比 C# 的 get/set 更灵活
java·python·c#
程序员与背包客_CoderZ1 天前
高性能分布式KV存储引擎RocksDB入门与C/C++编码实战
c语言·开发语言·数据库·c++·分布式·分布式数据库·rocksdb
欧叶冲冲冲1 天前
Python常见数据结构的CRUD(LeetCode高频版速查)
数据结构·python·leetcode
钱栈up1 天前
Mac 开发机一键发版不用切环境:我这样改造了团队的后端部署脚本Maven编译卡住20分钟?我靠两步定位到2处隐蔽编译错误
开发语言·python·macos
william_yangshun1 天前
【大模型部署实战】kimi-k3-in-c 中文版:用 176KB 纯 C99 引擎在 CPU 上跑 Kimi K3 上手指南
c语言·开发语言