How to join endpoint with IP adress from environmental variables, in Python - python

I'm trying to get the Kubernetes service IP using env variable to an endpoint inside a python app.
For example in NodeJs:
(`http://${process.env.AUTH_ADDRESS}/hashed-password/` + password);
using backticks and ${} IP address is fetched from the env variable
In Python I tried
opc.tcp://"+str(os.environ.get('USER_SERVICE_SERVICE_HOST'))+":4840/
but the result is actually something like ('10.98.191.127', 4840). I need it in a format like '10.98.191.127:4840' I have tried concatenate strings individually

Try to convert the port 4840 to str type. Something like:
str(os.environ.get('USER_SERVICE_SERVICE_HOST'))+":"+str(4840)
Something I would do is to use f-string format, something like:
f"{os.environ.get('USER_SERVICE_SERVICE_HOST')}:4840"

Related

Refer to variables dynamically

Context: I am creating a Django management command which will accept a positional argument. This argument is a location. My goal is to use the location value to refer to a corresponding variable.
I have a global variable named Boston_webhook. This is a simple string which contains a long URL which is just a MSteams webhook...
I have an additional global variable named Budapest_webhook which contains the same data type, but instead refers to a webhook related to the Budapest location.
In my script, a connector variable has to be defined in order to send the message to the correct place.
myTeamsMessage = pymsteams.connectorcard()
If someone entered python manage.py report Boston I want to insert this into the connector params, but I am unsure how to refer to variables dynamically.
Is it possible to refer to Boston_webhook when the location == 'Boston' using some sort of concatenation...?
something like myTeamsMessage = pymsteams.connectorcard(location + _webhook) would be ideal
I would like to avoid using conditionals as it is not scalable. I need to be able to add locations to the database without having to change code...
Use dictionary to map names of webhooks to webhooks itself - like this
webhooks = {
"Boston": "boston url",
"Budapest": "budapest url"
}
Now you can refer to your webhooks like this
# this will give you Boston webhook
myTeamsMessage = pymsteams.connectorcard(location + webhooks["Boston"])
This is simpliest way to do it. I think it would be better to create new class only for this and convert that class to string using a method , but this would be enough if you don't need anything more complex
I was able to determine a suitable solution;
myTeamsMessage = pymsteams.connectorcard(webhooks["{}".format(location)])
where the webhooks are stored in a dictionary keyed by location name.
i.e:
webhooks = {'Boston':'www.url.com',
'Budapest':'www.url1.com',
}
Thanks for the recommendations everyone!

Python: What is the BEST data structure to use in this scenario?

I am trying to make a DNS Server and Client in python. Where Server will have stored data like:
qtsdatacenter.aws.com 128.64.3.2 A
ww.ibm.com 64.42.3.4 A
www.google.com 8.6.4.2 A
localhost - NS
Basically Hostname IPaddress Type.
What would be the best datastructure to implement that will make searching for queries and outputting referenced data easy.
For example: send a String saying www.google.com from client, the server searches in its stored data table for the string match for hostname, returns in format
www.google.com 8.6.4.2 A.
Keep it simple like this. And use dictionary. Looks like your keys are going to be hashable and dictionaries possess O(1) average complexity. See this example:
dct = {"www.google.com" : "www.google.com 8.6.4.2 A",
"www.ibm.com" : " ww.ibm.com 64.42.3.4 A"}

Get all FQDN for an IP address in Python

I've the following problem : I'm actually making a script for an ovirt server to automatically delete virtual machine which include unregister them from the DNS. But for some very specific virtual machine there is multiple FQDN for an IP address example:
myfirstfqdn.com IN A 10.10.10.10
mysecondfqdn.com IN A 10.10.10.10
I've tried to do it with socket in Python but it return only one answer, I've also tried python with dnspython but I failed.
the goal is to count the number of type A record on the dns server
Anyone have an idea to do stuff like this?
That's outright impossible. If I am in the right mood, I could add an entry to my DNS server pointing to your IP address. Generally, you cannot find it out (except for some hints in some protocols like http(s)).
Given a zone file in the above format, you could do something like...
from collections import defaultdict
zone_file = """myfirstfqdn.com IN A 10.10.10.10
mysecondfqdn.com IN A 10.10.10.10"""
# Build mapping for lookups
ip_fqdn_mapping = defaultdict(list)
for record in zone_file.split("\n"):
fqdn, record_class, record_type, ip_address = record.split()
ip_fqdn_mapping[ip_address].append(fqdn)
# Lookup
ip_address_to_lookup = "10.10.10.10"
fqdns = ip_fqdn_mapping[ip_address_to_lookup]
print(fqdns)
Note: Using socket can be done like so - Python lookup hostname from IP with 1 second timeout
However this does require that DNS server that you are querying has correctly configured PTR reverse records.
https://www.cloudns.net/wiki/article/40/

Django Stripe API Key Issues

I have these lines (among other things) in my Django base settings file:
import os
STRIPE_PUBLIC_KEY = os.environ.get("STRIPE_PUBLIC_KEY", "your publishable test key")
STRIPE_SECRET_KEY = os.environ.get("STRIPE_SECRET_KEY", "your secret test key")
I created those two environment variables in my virtualenv like this:
export STRIPE_SECRET_KEY="sk_test_example"
export STRIPE_PUBLIC_KEY="pk_test_example"
When I run env | grep STRIPE, I get this:
STRIPE_SECRET_KEY=sk_test_example
STRIPE_PUBLIC_KEY=pk_test_example
But for some reason, I keep getting this Stripe error: ""Invalid API Key provided: \"\u003C**** ****** **** key\u003E\". This key contains at least one space. Please delete the spaces and try again."
I tried exporting the environment variables again, once without quotation marks and once with single quotation marks, and I got the same result, so I tried printing the STRIPE_SECRET_KEY and STRIPE_PUBLIC_KEY from the settings file, and it returned the defaults, "your publishable test key" and "your secret test key". So that's why there were spaces. But why weren't the environment variables getting picked up?
So I tried getting rid of the defaults in my base settings so the variables look like this:
STRIPE_PUBLIC_KEY = os.environ.get("STRIPE_PUBLIC_KEY")
STRIPE_SECRET_KEY = os.environ.get("STRIPE_SECRET_KEY")
That threw a NoneType error. I also tried the following:
STRIPE_PUBLIC_KEY = os.environ['STRIPE_PUBLIC_KEY']
STRIPE_SECRET_KEY = os.environ['STRIPE_SECRET_KEY']
That threw "KeyError: u'STRIPE_PUBLIC_KEY'". What do I need to change? I really don't want to hard-code these API keys.
It turns out that I'd forgotten (argh) to export the environment variables in my virtualenv postactivate file and was running the server in a different window, so once I put the Stripe API keys in the postactivate file, I needed to deactivate and activate the virtualenv before running the server.
For API keys, the quotes aren't necessary
export STRIPE_SECRET_KEY=sk_test_example
export STRIPE_PUBLIC_KEY=pk_test_example
It looks like the string format constructed with bash quotes is different than what Python is accepting. I don't know what formats these are, but this would definitely make sense.
Alternatively, you might want to look into a "dotenv" implementation such as django-dotenv.
This is a much more reliable way to work with strings like this. The problem is that when you're using different string formats (UTF-8 vs UTF-16 or Unicode), you may run into the situation where some program is expecting one format but receives another. The output you included is an example of what this looks like (hence my concern here).
Hope this helps!

How can I pass a string to pexpect spawn?

I want to ssh to another node on my network as part of a larger python script, I am using pexpect which works when I do something like this:
session=spawn('ssh root#172.16.210.254')
I want to replace the address with a variable so I can cycle through addresses in a list however when I try:
address = "172.16.210.253"
session=spawn('ssh root#'address)
It doesn't work as using address in this way is invalid syntax. What is the correct syntax for this?
session=spawn('ssh root#' + address) to concatenate the strings

Categories

Resources