Git | 项目开发中的权限管理

为什么需要权限管理?

项目开发中,访问各种外部资源时,经常会遇到各种权限认证的情形,比如发起 HTTP 请求时,通常需要提供 token 、私人 id 或其他密钥。通常来说,最好把权限的使用控制在一定的范围之内,将开发环境和生产环境的权限使用隔离开来。在协同开发的场景下,通常你可以在项目下建立两个不同的文件:config.iniconfig.ini.example,前者是你在本地运行代码需要的验证信息,后者是生产环境验证信息模板。但是,这样做有一个问题,当开发者 git push 的时候,岂不是两个验证文件大家都可以看到了?其实,要解决这个问题很简单,只需要在项目下新建一个 .gitignore 文件。.gitignore 文件的作用是告诉 Git 在推送本地修改的时候忽略哪些文件,比如该例中可以添加一行 *.ini,即项目中所有以 .ini 后缀结束的文件在推送中都会被忽略。这样,项目中的其他成员就看不到 config.ini 配置文件了,而他们可以按照你提供的 config.ini.example 模板在他们自己的开发环境中建立一个 config.ini 文件,并且也按照你的方法建立 .gitignore 文件,所以你也看不到他的配置信息。

Photo by Alan Hurt Jr. on Unsplash

configparser 在权限管理中的应用

下面简单介绍在 Python 中如何用 configparser 来完成项目中的参数配置需求。

在 Python 中,一般可以通过 configparser 库来灵活配置参数。Python2 下该模块名为 ConfigParser,到 Python3 才改为 configparser。ini 文件模板,

1
2
3
4
5
6
7
8
9
10
11
12
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

数据读取

configparser 的使用方法很简单,配置文件信息读取进来之后,默认 DEFAULT 的节不显示。你可以把每个 section 或变量的名字视为字典中一个个的 key,这样通过调用 key 就能取到对应的 value 值。有两种方式,一种是 section['key'],另外一种是 section.get('key'),两种方式的效果一样。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('example.ini')
['example.ini']
>>> config.sections()
['bitbucket.org', 'topsecret.server.com']
>>> 'bitbucket.org' in config
True
>>> 'bytebong.com' in config
False
>>> config['bitbucket.org']['User']
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topsecret.server.com']
>>> topsecret['ForwardX11']
'no'
>>> topsecret['Port']
'50022'
>>> for key in config['bitbucket.org']: print(key)
...
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config['bitbucket.org']['ForwardX11']
'yes'

有一点需要注意的地方,configparser 并不会去猜测配置文件中的数据类型,因为它会把所有的数据都视为字符串型,这就意味着如果你需要其他类型的数据,需要额外的转换数据操作。比如,对整数型和浮点型的需求

1
2
3
4
>>> int(topsecret['Port'])
50022
>>> float(topsecret['CompressionLevel'])
9.0

也可以这样来实现

  • getint()
  • getfloat()
1
2
3
4
>>> config.getint('topsecret', 'Port')
50022
>>> config.getfloat('topsecret', 'CompressionLevel')
9.0

比如,对逻辑判断型 boolean 数据的需求

  • getboolean()
1
2
3
4
5
6
>>> topsecret.getboolean('ForwardX11')
False
>>> config['bitbucket.org'].getboolean('ForwardX11')
True
>>> config.getboolean('bitbucket.org', 'Compression')
True

数据写入

数据写入的方式也很简洁,比如用 add_section('new section') 方法给配置文件添加与 [bitbucket.org] 同等级别的节 new section。用 set() 方法给新添加的节设置新的配置信息,比如

1
2
3
config.set('new section', 'an_int', '99') # 整型
config.set('new section', 'a_boolean', 'true') # 布尔型
config.set('new section', 'a_float', '2.17') # 浮点型

本文主要介绍了在项目开发中权限处理的背景以及实现方式,简单介绍了 configparser 的使用方法,深入了解可以继续参考官方文档。

推荐阅读

  1. Git忽略文件.gitignore的使用
  2. 14.2. configparser — Configuration file parser
------本文结束,欢迎收藏本站、分享、评论或联系作者!------
点击查看
赠人玫瑰 手有余香
0%