python - how to pass slack token to python app from dockerfile - docker

I have my python app, in which i am passing my slack tokens via json file.
so my config.json is :
{
"slack_bot_token":"xoxb-12345789",
"slack_signing_secret":"AAA23245GJ"
}
So my slackeventsapp.py is :
from slackeventsapi import SlackEventAdapter
from slackclient import SlackClient
import json
tokens = {}
with open('config.json') as json_data:
tokens = json.load(json_data)
EVENT_ADAPTER = SlackEventAdapter(tokens.get("slack_signing_secret"), "/slack/events")
SLACK_CLIENT = SlackClient(tokens.get("slack_bot_token"))
def PostMsg(channel, text):
SLACK_CLIENT.api_call("chat.postMessage", channel=channel, text=text)
so I need to pass the two values slack_signing_secret and slack_bot_token via dockerfile. Please help how cna we pass this.

Copy the config file using your Dockerfile. This way the config file will be in the built image.
Mount a volume where the config file is kept.
There might be other ways.

Related

Is unix file path a valid URL?

Suppose we have a string /path/to/file, when I use urlparse of Python, it will treat the string as a valid URL and return the following result:
from urllib.parse import urlparse
urlparse('/path/to/file')
# ParseResult(scheme='', netloc='', path='/path/to/file', params='', query='', fragment='')
But if I do the same thing with JavaScript, it will throw the following error
new URL('/path/to/file')
// Uncaught TypeError: Failed to construct 'URL': Invalid URL
I am wondering which implemetation is right. Shall a unix file path treat as a valid URL? I don't dive in to the RFCs, but personally I prefer the way of Python as it makes it clear to distingiush local file or remote resource by parsing it and checking the scheme field. It's useful when you write a program that allow use to load file from local or remote.
Update:
According to the document provided by Alexei Levenkov
: The Fine Manual on JavaScript it says
url: A string ... that represents an absolute or relative URL. If url is a relative URL, base is required, and will be used as the base URL. If url is an absolute URL, a given base will be ignored.
In JavaScript it will not throw error if base parameters is provided
new URL('/path/to/file', 'file://')
But it still have gap with the implement of python when input string is a relative path ./path/to/file.
In JavaScript it will ignore the ./ but Python will still keep it.
JavaScript:
new URL('/path/to/file', 'file://')
new URL('./path/to/file', 'file://')
// both yeild the same result:
// URLĀ {origin: 'file://', protocol: 'file:', pathname: '/path/to/file'}
Python:
from urllib.parse import urlparse
urlparse('/path/to/file')
# ParseResult(scheme='', netloc='', path='/path/to/file', params='', query='', fragment='')
urlparse('./path/to/file')
# ParseResult(scheme='', netloc='', path='./path/to/file', params='', query='', fragment='')

Generate files with one input to multiply outputs

I'm trying to create a code generator that takes input a JSON file and generates multiple classes in multiple files.
And my question is, is it possible to create multiple files for one input using build from dart lang?
Yes it is possible. There are currently many tools in available on pub.dev that have code generation. For creating a simple custom code generator, check out the package code_builder provided by the core Dart team.
You can use dart_style as well to format the output of the code_builder results.
Here is a simple example of the package in use (from the package's example):
import 'package:code_builder/code_builder.dart';
import 'package:dart_style/dart_style.dart';
final _dartfmt = DartFormatter();
// The string of the generated code for AnimalClass
String animalClass() {
final animal = Class((b) => b
..name = 'Animal'
..extend = refer('Organism')
..methods.add(Method.returnsVoid((b) => b
..name = 'eat'
..body = refer('print').call([literalString('Yum!')]).code)));
return _dartfmt.format('${animal.accept(DartEmitter())}');
}
In this example you can use the dart:io API to create a File and write the output from animalClass() (from the example) to the file:
final animalDart = File('animal.dart');
// write the new file to the disk
animalDart.createSync();
// write the contents of the class to the file
animalDart.writeAsStringSync(animalClass());
You can use the File API to read a .json from the path, then use jsonDecode on the contents of the file to access the contents of the JSON config.

Vite+SvelteKit - Environment variables hyper-protection

I am trying to make a POC and I'm such making a really simple use-case.
In there, I use a src/lib/db.ts who, for our interest, contains this code
console.log(import.meta.env.MONGO_URI, import.meta.env.SSR);
giving
undefined true
Of course, my .env file contains a definition for MONGO_URI, I tried with VITE_MONGO_URI and could see the value.
I know a way to expose it is to use VITE_MONGO_URI but my point is exactly not to expose it on the client-side.
I checked and the file db.ts is not bundled with the client, even the import.meta.env.SSR being true shows that the bundler knows it's happening on the server.
Question: How to access my private environment variables server-side ?
EDIT: As specified by Shriji Kondan, the API for this purpose has been created now : here
You could use dotenv on the server side, assuming you are using node-adapter, you can have a file _constants.ts in your app
import 'dotenv/config';
export const MONGO_URI = process.env.MONGO_URI;
and then import this variable into your script.
It's not very awesome to put secrets on client-side code. It should be either utilities.ts with a performed action SUPER_SECRET_API_KEY="$ecret#p1Key" in .env file, then request it via in src/lib/utilities/utility.js as explained here :
import { SUPER_SECRET_API_KEY } from '$env/static/private';
export function performApiAction() {
const apiInstance = initialiseApi({key: SUPER_SECRET_API_KEY});
}
or from page.server.ts via form actions as stated here which is preferable way but it's more complex.

How do you load a file (.csv) into a Beeware/Briefcase application?

I am using kivy as the GUI and Briefcase as a packaging utility. My .kv file is in the appname/project/src/projectName/resources folder. I also need a .csv file, in the same folder, and want to use pandas with it. I have no problem with importing the packages (I added them to the .toml file). I can't use the full path because when I package the app, the path will be different on each computer. Using relative paths to the app.py file does not work, giving me a file not found error. Is there a way to read a file using a relative path (maybe the source parameter in the .toml file)?
kv = Builder.load_file('resources/builder.kv')
df = pd.read_csv('resources/chemdata.csv')
class ChemApp(App):
def build(self):
self.icon = 'resources/elemental.ico'
return kv
I just encountered and solved a similar problem with Briefcase, even though I was using BeeWare's Toga GUI.
In my case, the main Python file app.py had to access a database file resources/data.csv. In the constructor of the class where I create a main window in app.py, I added the following lines (The import line wasn't there, but included here for clarification):
from pathlib import Path
self.resources_folder = Path(__file__).joinpath("../resources").resolve()
self.db_filepath = self.resources_folder.joinpath("data.csv")
Then I used self.db_filepath to successfully open the CSV file on my phone.
__file__ returns the path to the current file on whatever platform or device.

Writing to a json file in workspace using Jenkins

I've a jenkins job with few parameters setup and I've a JSON file in the workspace which has to be updated with the parameters that I pass through jenkins.
Example:
I have the following parameters which I'll take input from user who triggers the job:
Environment (Consider user selects "ENV2")
Filename (Consider user keeps the default value)
I have a json file in my workspace under run/job.json with the following contents:
{
environment: "ENV1",
filename: "abc.txt"
}
Now whatever the value is given by user before triggering a job has to be replaced in the job.json.
So when the user triggers the job, the job.json file should be:
{
environment: "ENV2",
filename: "abc.txt"
}
Please note the environment value in the json which has to be updated.
I've tried https://wiki.jenkins-ci.org/display/JENKINS/Config+File+Provider+Plugin plugin. But I'm unable to find any help on parameterizing the values.
Kindly suggest on configuring this plugin or suggest any other plugin which can serve my purpose.
Config File Provider Plugin doesn't allow you to pass parameters to configuration files. You can solve your problem with any scripting language. My favorite approach is using Groovy plugin. Hit a check-box "Execute system Groovy script" and paste the following script:
import groovy.json.*
// read build parameters
env = build.getEnvironment(listener)
environment = env.get('environment')
filename = env.get('filename')
// prepare json
def builder = new JsonBuilder()
builder environment: environment, filename: filename
json = builder.toPrettyString()
// print to console and write to a file
println json
new File(build.workspace.toString() + "\\job.json").write(json)
Output sample:
{
"environment": "ENV2",
"filename": "abc.txt"
}
With Pipeline Utility Steps plugin this is very easy to achieve.
jsonfile = readJSON file: 'path/to/your.json'
jsonfile['environment'] = 'ENV2'
writeJSON file: 'path/to/your.json', json: jsonfile
I will keep it simple. A windows batch file or a shell script (depending on the OS) which will read the environment values and open the JSON file and make the changes.

Resources