“Standard” way of creating config file suitable fo

2019-04-28 02:29发布

My application was 100% developed in pure Python. I found very useful and easy to create a config file with .py extension and than simply load it in every code. Something like this:

ENV = 'Dev'
def get_settings():
    return eval(ENV)

class Dev():
    ''' Development Settings '''

    # AWS settings
    aws_key = 'xxxxxxxxxxxxx'
    aws_secret = 'xxxxxxxxxxxxxxxxx'

    # S3 settings
    s3_bucket = 'xxxxxxxxxx'
    ...
    ...

And than in my code I just import this file and use settings, this way I have one file that easy to manage and that contains all aprameters I need.

Howewer recently I had to move part of my code to Java. And now I'm struggling with configurations.

Question:

What are the "standard" way to create a config that would be easily accessible from both languages? (My Java skills are very limited, if you can five me a brief example in Java it would be great)

2条回答
Deceive 欺骗
2楼-- · 2019-04-28 02:41

Have a look at ConfigParser in Python

The syntax on this file looks like this:

[Section]
my_option = 12.2
my_option2 = other_value

[Section2]
my_voption = my_value

You read it this way:

import ConfigParser

config = ConfigParser.ConfigParser()
config.read('example.cfg')
config.getfloat('Section', 'my_option') # returns 12.2

It works for a couple of types and if you can't find a type, you can use the eval function in Python. Finding an equivalent to Java shouldn't be too hard. Or even parsing this file using Java shouldn't be too hard.

查看更多
淡お忘
3楼-- · 2019-04-28 02:41

Use standard configuration files : XML or .properties for example.

For XML, you can use JDOM in Java, minidom in Python.

For .properties, Java handles this nativaly via class Properties and Python can handle this via ConfigParser

查看更多
登录 后发表回答