I want to implement a check if import pdblp is active and if not exit the session.
I note from this link (Bloomberg Anywhere + pdblp or xbbg + not logged in) that a session:
remains logged in for 3 days.
is logged out if a session is opened on another pc.
Therefore, i want to implement a try-execpt block like this:
import pdblp
# check if connected
try:
con = pdblp.BCon(timeout=5000)
con.start()
except Exception as e:
print('not logged in:', e)
my question is, would the above be sufficient to validate the connection ?
(ie. would the above throw an error, e).
TL;DR
Use the newer blp package instead of blpapi, which is no longer supported by the creator.
pip install blp
try:
from blp import blp
con = blp.BlpQuery().start()# change debug to true to see issues
except:
print('NO BLOOMBERG')
Yes, your try-except is sufficient. The except statement will throw you the error to know that the Bloomberg connection is not working (the link you included to the other SO article correctly noted that the python API will only work under the same conditions that the Excel API does for Bloomberg).
However, it was troublesome for me that con = pdblp.BCon(timeout=5000) con.start() would try to connect for nearly 1 minute. The new blp package will kick out an error in 17 seconds. Just change your con to the new .start()
Related
i recently started experimenting in the RingCentral sandbox environment and facing issues with this part of the code
rcsdk = SDK(CLIENTID,CLIENTSECRET,SERVERURL)
platform = rcsdk.platform()
try:
platform.login(USERNAME,EXTENSION,PASSWORD,JWT)
except Exception as e:
sys.exit("Unable to authenticate to platform. Check credentials." + str(e))
I went to know if there is an alternative to code
Looking at your code snippet, I can see that the platform.login() function signature is incorrect as you are passing extra argument.
Correct function signatures in Python are:
Logging with username, password flow: platform.login(USERNAME, EXTENSION, PASSWORD)
Logging with JWT : platform.login( jwt=JWT_TOKEN )
Make sure to replace the UPPERCASE String with the actual credential found in RingCentral Developer Portal for your app's sandbox environment and it should work.
Reference:
https://developers.ringcentral.com/guide/authentication
I am connecting to a db using jaydebeapi and a jdbc driver using the following snippet, that works fine when the all parameters are correctly specified.
I am storing my credentials in environment variables e.g. os.environ.get('credentials')
import jaydebeapi as dbdriver
import os
cnxn = None
server_name=''
server_jdbc_port=
server_database=''
name_env_credentials=''
name_env_pwd=''
try:
driver_path = "XXXXXXX"
conn_uri = "jdbc:://%s:%s/%s?" % (server_name,server_jdbc_port, server_database)
cnxn = dbdriver.connect( "XXXXXXX",
conn_uri,
driver_args = {"user": os.environ.get(name_env_credentials),
"password": os.environ.get(name_env_pwd)},
jars = driver_path)
print('Connection open')
except (Exception) as error:
raise error
finally: # in any case close connection and free resources
if cnxn is not None:
cnxn.close()
print('Database connection closed.')
If there are some errors in my credentials/access rights I get, which is ok.
java.sql.SQLExceptionPyRaisable: java.sql.SQLException: authentication error:
Insufficient privileges to connect to the database 'XXXXX'
However, when I wrap the above into a function, pytest-parametrized on server_name,server_jdbc_port,server_database,name_env_credentials,name_env_pwd.
######test_issue.py
#pytest.mark.parametrize("server_name,server_jdbc_port,server_database,name_env_credentials,name_env_pwd", testdata)
def test_connectivity():
# above code
When I run
pytest test_issue.py
and an error in raised, the I find my credentials in plain text in the logs, which is a problem.
To be precise, I am not seeing the content name_env_credentials (would be acceptable) but really the contents of os.environ.get(name_env_credentials) (below for example MYPLAINTEXTUSERNAME) in the test logs/tracebacks
test_issue.py:56: in test_connectivity
cnxn = dbdriver.connect( "--------",
/opt/conda/lib/python3.8/site-packages/jaydebeapi/__init__.py:412: in connect
jconn = _jdbc_connect(jclassname, url, driver_args, jars, libs)
[........]
driver_args = {'password': MYPLAINTEXTPASSWORD, 'user': MYPLAINTEXTUSERNAME}
[........]
jaydebeapi.__version__='1.2.3'
You are using the default traceback logger of pytest, which also logs the arguments passed to a specific function. One way to solve this kind of leak is to use another traceback mode. You can find the general documentation at this
link. In that link you can find two interesting traceback modes:
--tb=short
--tb=native
Both give you all the information you need during your specific test since:
They still give you information about the tests failed or succeded
Since you are using parametrized tests, the logs about failures will look like FAILED test_issue.py::test_connectivity[server_name-server_jdbc_port-server_database-name_env_credentials-name_env_pwd], in this way you can identify the actual failing test
Mind that this solution, while avoiding to log the credentials used at test time, these credentials used during testing must not be the same that will be used outside the test environment. If you are concerned with the fact that in case of failures in production, the logger could leak your credentials, you should setup you logger accordingly and avoid to log the default text of the exception.
I'm trying to send an email using SendGrid within Azure Machine Learning. This is initially just a basic test email to ensure it is working correctly.
The steps I have taken:
Pip installed SendGrid;
Zipped the SendGrid download and uploaded as a dataset to AML platform;
Attempted to run the example SendGrid Python code (which can be seen below):
I have copied steps in similar posts concerning uploading modules to AML here and here as well as ensuring the correct settings for the SendGrid API key were established on setup here.
def azureml_main():
import sendgrid
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
message = Mail(
from_email='xxx#xyz.com',
to_emails='xxx#xyz.com',
subject='Sending with Twilio SendGrid is Fun',
html_content='<strong>and easy to do anywhere, even with Python</strong>')
try:
sg = SendGridAPIClient(os.environ.get('SG API Code'))
response = sg.send(message)
print(response.status_code)
print(response.body)
print(response.headers)
except Exception as e:
print(e)
No error message is returned in the terminal. To me this indicates there weren't any issues with the code, yet no emails have been received/sent.
python ScheduleRun.py
azureuser#will1:~/cloudfiles/code/Users/will/Schedule$
azureuser#will1:~/cloudfiles/code/Users/will/Schedule$ python ScheduleRun.py
azureuser#will1:~/cloudfiles/code/Users/will/Schedule$
Twilio SendGrid developer evangelist here.
When you run the code nothing is printed, which is concerning as neither the success or error prints are called.
If the code you have shared is the entirety of the file then I think the code is simply not running. You have defined a function but you have not called the function itself.
Try calling azureml_main() on the last line of the file:
print(response.headers)
except Exception as e:
print(e)
azureml_main()
One other thing that concerns me is this line:
os.environ.get('SG API Code')
It looks as though you intend to actually place your SG API Key in the call to os.environ.get. Instead, that string should be the identifier for an environment variable that you have set. For example, you should set the SendGrid API key as an environment variable called SENDGRID_API_KEY and then in your code fetch the API key by calling os.environ.get("SENDGRID_API_KEY"). Check out this post on working with environment variables in Python for more.
I want to write a simple slack bot, which responds a given string to # mentions, however I am not able to make the official documentation code to work.
I gave all OAuth permission to the bot and have the following code:
from slack import RTMClient
#RTMClient.run_on(event="message")
def gravity_bot(**payload):
data = payload['data']
print(data.get('text'))
try:
rtm_client = RTMClient(
token="my_token_auth_code",
connect_method='rtm.start'
)
print("Bot is up and running!")
rtm_client.start()
except Exception as err:
print(err)
I think the connection is established, as the "Bot is up and running" message appears, however on the slack channel to bot seems to be offline, also I am not able to get any response in the terminal, not for direct messages, not for channel messages even after inviting the bot to given channels.
Sorry couldn't let this one go.. I figured it out and here are the steps:
Create a "Classic" app in Slack (this is the only way to get the appropriate scopes), just click this link: https://api.slack.com/apps?new_classic_app=1
From the "Add features and functionality" tab click on "bots":
Click the "Add Legacy Bot User" button (this will add the "rtm.stream" scope that you need, but that you cannot add manually)
From the basic information page, install your app in a workspace
From the OAuth & Permissions page, copy the "Bot User OAuth Access Token" (the bottom one)
Run the following code (slightly modified version of the code in the docs)
from slack_sdk.rtm import RTMClient
# This event runs when the connection is established and shows some connection info
#RTMClient.run_on(event="open")
def show_start(**payload):
print(payload)
#RTMClient.run_on(event="message")
def say_hello(**payload):
print(payload)
data = payload['data']
web_client = payload['web_client']
if 'Hello' in data['text']:
channel_id = data['channel']
thread_ts = data['ts']
user = data['user']
web_client.chat_postMessage(
channel=channel_id,
text=f"Hi <#{user}>!",
thread_ts=thread_ts
)
if __name__ == "__main__":
slack_token = "<YOUR TOKEN HERE>"
rtm_client = RTMClient(token=slack_token)
rtm_client.start()
Previous answer:
Hmm, this is tricky one... According to the docs this only works for "classic" Slack apps, so that might be the first pointer. It explicitly says that you should not upgrade your app. Furthermore, you'll need to set the right permissions (god knows which ones) by selecting the "bot" scope.
Honestly, I haven't been able to get this running. Looks like Slack is getting rid of this connection method, so you might have more luck looking into the "Events API". I know it's not the ideal solution because its not as real-time, but it looks better documented and it will stay around for a while. Another approach could be polling. Its not sexy but it works...
My guess is that your problem is that there is not a valid connection, but there is no proper error handling in the Slack library. The message is printed before you actually connect, so that doesn't indicate anything.
I have deployed this Python app on Heroku and i want it to connect to a MongoDB Atlas cluster. I used my string to connect to the cluster, but for some reason i keep getting raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: bad auth Authentication failed. I checked twice and both the user and the password are correct. Any idea on why this is happening?
from pymongo import MongoClient
import time
import random
import time
import datetime
client = MongoClient('mongodb+srv://USER:<MYPASSWORD>#test-2liju.mongodb.net/test?retryWrites=true')
db = client.one
mycol = client["tst"]
while True:
test = int(random.randrange(-99999990,90000000,1))
dic = {"num": test}
result = db.tst.insert_one(dic)
print(test)
time.sleep(5)
Stupid error, i had to type MYPASSWORD instead of <MYPASSWORD>, without the <>
Don't use any special char in password, like '+' or '='.
I use OpenSSL to generate a password like u4wY9AOwnOLMY+h9EQ==. Came across bad auth Authentication failed.
After using MongoDB Compass it told me don't use special char, so I remove those and use like 'u4wY9AOwnOLMYh9EQ'.
Then it works.
check the compatibility of the version of the Python driver you choose from the Mongodb Atlas Connections. versions above 3.4 are not supported by mongoengine flask