passing a list in python to generate url - python

I have to import my config.py file in my code and then basically pass the REPOS_TO_CHECK values to a function which should be in the form of a list such that when I pass the list to my build_url function which generates a url when the REPOS_TO_CHECK variable is passed to it from the config.py file
I have to generate the url like GET /repos/:owner/:repo
GITHUB_URL = 'https://testurl.com'
how do I pass the REPOS_TO_CHECK parameter from the config.py file as a list so that when I pass
def build_url(['owner','repo']):
the url generated will be https://testurl.com/:owner/:repo
:owner, :repo are in the REPOS_TO_CHECK in the config.py file.
I can access the config.py file by importing config.py in my code and then accessing the values by using the config. for example: config.GITHUB_URL ,gives me 'https://testurl.com'
This is my config file:
GITHUB_URL = 'https://testurl.com'
GITHUB_ACCESS_TOKEN = 'access token'
REPOS_TO_CHECK = [
('owner1', 'repo1'),
('owner2', 'repo2'),]

You can import your config.py as any other file given it's in the same folder: (otherwise navigate to it)
import config
Then you can call the variable like config.REPOS_TO_CHECK
To generate the url you can simply use the variables given in the function call:
If you're using python 3.6 use f strings:
def generate_url(list_here):
return f'http://test.com/{list_here[0]}/{list_here[1]}'
Else use .format()
def generate_url(list_here):
return 'http://test.com/{0}/{1}'.format(list_here[0], list_here[1])

Related

read variables from a blank file in python

If I have a folder structure like the attached picture. The test.config.py is an empty file.
The default.py contains name variables indicate default folder root and addin information
local_root = r'c:\temp\project\cache'
local_input = local_root + r'inputs'
local_output = local_root + r'outputs'
addin_location = r'c:\user\...
addin_name = r'project_addin'
addin_version = r'1.1'
The setting.py contains name variables to overwrite addin information for testing.
addin_location = r'd:\user\...
addin_name = r'project_addin'
addin_version = r'2.1'
I want to import all variables from default.py and all variables from setting.py to init.py. Then overwrite variables with the same names imported from default.py use setattr(). i.e the addin_location, addin_name, and addin_version in default.py share the same name as variables in setting.py, thus overwrite those with setting.py.
Lastly, for any test.py files in test folder, it cannot refers to any of the variables using default.names or setting.names, but instead use config.names (basically the config.py should contain all variable names from default.py with overwritten information from setting.py, so that the codes in test.py only refer to the variable names in config.py). I have manually updated all reference to config.py but don't know how to put all variable names to config.py as it is an empty file. I think need to write some functions in init.py to dump those variable names to config.py
Thanks for the help.
Do you need to keep a track of those config in a file or do you just want to access all information from the combine default.py + any setting.py overwrite ?
For the latter, I think you can use dataclasses:
# default.py
from dataclasses import dataclass
# Here I am defining the default parameters for the class instance
#dataclass
class Config:
local_root: str = r'c:\temp\project\cache'
local_input: str = local_root + r'inputs'
local_output: str = local_root + r'outputs'
addin_location: str = r'c:\user\...'
addin_name: str = r'project_addin'
addin_version: str = r'1.1'
Then in setting you can instantiate the class by replacing by placing all overwriting values in a dict.
# setting.py
from .default import Config
overwrite_settings = {
"addin_location": r'd:\user\...',
"addin_name": r'project_addin',
"addin_version": r'2.1'
}
config = Config(**overwrite_settings)
Then in your test file you can import the config object and access the variable as follow:
# test.py
from .setting import config
my_path_root = config.local_root
And if you want to use init just instantiate the class in the init.py file and import the config with it:
#init.py
from .setting import overwrite_settings
from .default import Config
config = Config(**overwrite_settings)
For the former I am not sure how to save directly into a ready to use python file. Especially at run time, it might be tricky.
But if you want to keep a track of the config that you run you can add a
__post_init__ method to your class in order to save it to a json for example:
# default.py
from dataclasses import dataclass
#dataclass
class Config:
local_root: str = r'c:\temp\project\cache'
local_input: str = local_root + r'inputs'
local_output: str = local_root + r'outputs'
addin_location: str = r'c:\user\...'
addin_name: str = r'project_addin'
addin_version: str = r'1.1'
def __post_init__(self):
with open('run_config.json', 'r') as file:
json.dump(self.__dict__, file)
Hope this helps.

How to access Environment Variables in Django with Django Environ?

I'm a Node developer but I need to create a Django app (i'm totally beginner in Django).
I need to read some data from an API but ofc, I shouldn't hardcode the API url.
So having API_BASE_URL=api.domain.com in my .env file, in Node I would access the variables in my functions this way:
import ('dotenv/config');
import axios from 'axios';
baseUrl = process.env.API_BASE_URL;
function getApiData() {
return axios.get(baseUrl);
}
So how would be the Python/Django version of it?
Saying I have the function bellow:
import ???
def get_api_data():
url = ????
import environ
# reading .env file
environ.Env.read_env()
def get_api_data():
url = env('API_BASE_URL')
Let's say you have a .env file saved in the same directory as your manage.py file.
You can then go to settings.py and do:
from decouple import config
API_BASE_URL = config('API_BASE_URL')
Assuming your .env file looks like:
API_BASE_URL='some.url'

Passing Config file Path as variable in function

I am reading a locally stored config file in my project folder. When the location for config file is hardcoded in fileconfig.read('C:/FileConfig.ini') there are no issues. But, when I pass the path variable of file in same function fileconfig.read(path) it gives empty value.
Please can anyone let me know how to provide file path in function fileconfig.read(path) function.
Python code:
def read_config_from_file(path):
fileconfig = configparser.ConfigParser()
# fileconfig.read('C:/FileConfig.ini') # works perfectly
fileconfig.read(path) # Empty Value
configfromFileDict = dict()
for section in fileconfig.sections():
# configfromFileDict[section] = {}
for option in fileconfig.options(section):
print(option, fileconfig.get(section, option))
configfromFileDict[option] = fileconfig.get(section,option)
return configfromFileDict
configurations = read_config_from_file('C:/FileConfig.ini')

Python: Read all config values from .ini file and store in Dictionary and access in other files

I have a config.ini file. When my python application starts, I want to read all config values and store them in a dictionary. Then this dictionary should be available in all other files
[sql]
Server=localhost
UserId=root
[url]
url1=localhost
UserId1=root
I have a Class1.py:
from configparser import SafeConfigParser
class class1(object):
def __init__(self, *file_name):
parser = SafeConfigParser()
parser.read('config.ini')
self.__config__ = {}
for section in parser.sections():
self.__dict__.update(parser.items(section))
configData= class1('config.ini')
In my main file, I am not able to access configData.Server
from class1 import configData
print(configData.Server)
Strangely, the config keys are automatically getting converted to lowercase.
Even my key is Server, it is getting changed to server.
So while configData.Server throws error configData.server works fine.

How to pass variable values to another config parameters?

[plugin_jira]
maxuser=
finduser=
endpoint="https://nepallink.atlassian.net/rest/api/latest/user/search?startAt=0&maxResults={maxi}&username={manche}%".format(maxi=maxresult,manche=user_find)
This is my config file , in the endpoints item why I am using the format is so that I can pass a variable to it in my script.The script where it is running is below ,my main.py
maxresult = config.get('plugin_jira', 'maxuser')
user_find = config.get('plugin_jira', 'finduser')
endpoint = config.get('plugin_jira', 'endpoint')
Now what I am confused is when I call the endpoints values in the script it just fetching what is in the config without the variable values that got defined just above it.
How can I make the variable value of maxresult and user_find added to endpoints which is defined to access it.
In your config file, import the variables from main.py as following.
Config file:
from main import maxresult, user_find
[plugin_jira]
endpoint="https://nepallink.atlassian.net/rest/api/latest/user/search?startAt=0&maxResults={maxi}&username={manche}%".format(maxi=maxresult,manche=user_find)
This will allow you to access the required variables to your endpoints.
Hope it helps!

Categories