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.
Related
I am working on a python project which includes using the Youtube\Google API, accessing public playlists.
The code works fine in the Pycharm IDE but after using Pyinstaller to build it into an .exe file, it crashes and prints 'Crashed at youtube build stage'
from googleapiclient.discovery import build
try:
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = json_path
credentials = google.oauth2.service_account.Credentials.from_service_account_file(json_path)
print("credentials=",credentials)
youtube = build(serviceName='youtube', version='v3', developerKey=yt_api_key, num_retries=3,credentials=credentials)
except Exception as e:
print(f"Crashed at youtube build stage \n\nError: {e}")
try:
youtube_playlist=youtube.playlists().list(part='contentDetails,id',id=youtube_playlist_id)
youtube_playlist=youtube_playlist.execute()
except Exception as e:
print(e,"\nERROR HERE")
When running on the IDE the build succeeds, but fails at the 2nd try except section.
The error given is :
('invalid_scope: Invalid OAuth scope or ID token audience provided.', {'error': 'invalid_scope', 'error_description': 'Invalid OAuth scope or ID token audience provided.'})
I looked at the google API and the playlists() method and I didn't find any place to use the Oauth credentials there.
When running on the EXE it simply prints :
Crashed at youtube build stage
Error: name: youtube version: v3
According the the build() documentation found here https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.discovery-module.html#build
I found that the function raises an error when it can't create an mTLS connection.
Why can't it do so when the code is ran from an .exe file but manages when called from the IDE?
I thought the .exe created with Pyinstaller would work as it does on Pycharm, but it appears not to.
Not sure why TLS fails to set up.
Edit: added credentials and Oauth2 and another error appears.
It manages to build it but right afte
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 attempted to run the code below and am getting an error that states:
HTTP Error code: 403: Forbidden: Authentication succeeded but account is not authorized to access this resource.
from searchtweets import ResultStream, gen_rule_payload, load_credentials, collect_results
import requests
premium_search_args = load_credentials("/home/dirname/twitter_keys.yaml",
yaml_key="search_tweets_premium",
env_overwrite=False)
rule = gen_rule_payload("basketball", results_per_call=100) # testing with a sandbox account
print(rule)
from searchtweets import collect_results
tweets = collect_results(rule,
max_results=100,
result_stream_args=premium_search_args)
# print(tweets.all_text)
[print(tweet.all_text, end='\n\n') for tweet in tweets[0:10]];
My YAML file looks like this:
search_tweets_premium:
account_type: premium
endpoint: https://api.twitter.com/1.1/tweets/search/fullarchive/dev.json
consumer_key: AAAAAAAAAAAAAAAAAAAAA
consumer_secret: BBBBBBBBBBBBBBBBBBBBBBBBBBB
Only other thing to note is that I am using the free/sandbox service.
Any ideas if I am doing anything wrong in the code, the YAML, and/or within my Twitter developer account?
You'll need to go to https://developer.twitter.com/en/account/environments
There you should be able to see the various development environments that you have. You can create one should they not have been created.
The dev environment label would then be the thing you use to replace in your endpoint.
In my example, it would be:
https://api.twitter.com/1.1/tweets/search/fullarchive/development.json
If that still doesn't work, you might need to include a bearer token in your YAML file.
I'm using the following Python code from Slack's "Migrating to 2.x" github docs
from slackclient import SlackClient
slack_token = os.environ["SLACK_API_TOKEN"]
client = SlackClient(slack_token)
def say_hello(data):
if 'Hello' in data['text']:
channel_id = data['channel']
thread_ts = data['ts']
user = data['user']
client.api_call('chat.postMessage',
channel=channel_id,
text="Hi <#{}>!".format(user),
thread_ts=thread_ts
)
if client.rtm_connect():
while client.server.connected is True:
for data in client.rtm_read():
if "type" in data and data["type"] == "message":
say_hello(data)
else:
print "Connection Failed"
For the SLACK_API_TOKEN, I am using the Bot User OAuth Access Token for my app, found here:
The error I am getting is the following:
Failed RTM connect
Traceback (most recent call last):
File "/Users/.../slackbot/slackbot_env/lib/python3.8/site-packages/slackclient/client.py", line 140, in rtm_connect
self.server.rtm_connect(use_rtm_start=with_team_state, **kwargs)
File "/Users/.../slackbot/slackbot_env/lib/python3.8/site-packages/slackclient/server.py", line 168, in rtm_connect
raise SlackLoginError(reply=reply)
slackclient.server.SlackLoginError
Connection Failed
Why am I getting this error?!?!?!
Other context:
I am on a Mac, unlike others who have had issues online using Windows
machines.
I am running the code locally, in a virtual env, via
python script.py in my terminal.
I last successfully ran this in December, and have seen that Slack dropped support for the RTM API (?) Dec 31st 2019?
The app has been reinstalled to my workspace, and the keys did not change.
I think it may be something I need to configure/change/set/refresh on the api.slack.com/apps side, since it broke without any code changes occurring.
Why am I focusing on debugging the example for 1.x? My code was previously working using rtm_connect / 1.x using the same commands as the example code, and without any code changes it has stopped working. My code and the example code yield the same errors, so I'm using the sample code to make debugging easier. I'd like to fix this before starting the process of migrating to 2.x, so I can start with working code before embarking on a long series of changes that can introduce their own errors.
I do not think this issue is related to the Bot User OAuth Access Token, in my view you are using the right one (xoxb-). However, this issue might be related to the Slack App. Note that RTM isn't supported for the new Slack App granular scopes (see python client issue #584 and node client issue #921). If you want to use RTM, you should create rather a classic slack app with the OAuth Scope bot.
I not sure if this is the reason, but I ran into the same issues before.
The answer I found on the Slack Github is that new xoxob-* doesn't support RTM.
Please reference this web:
- https://github.com/slackapi/python-slackclient/issues/326.
So I use my OAuth Access Token instead of Bot User OAuth Access Token.
I'm new to Python, new to the jira-python library, and new to network programming, though I do have quite a bit of experience with application and integration programming and database queries (though it's been a while).
Using Python 2.7 and requests 1.0.3
I'm trying to use this library - http://jira-python.readthedocs.org/en/latest/ to query Jira 5.1 using Python. I successfully connected using an unauthenticated query, though I had to make a change to a line in client.py, changing
I changed
self._session = requests.session(verify=verify, hooks={'args': self._add_content_type})
to
self._session = requests.session()
I didn't know what I was doing exactly but before the change I got an error and after the change I got a successful list of project names returned.
Then I tried basic authentication so I can take advantage of my Jira permissions and do reporting. That failed initially too. And I made the same change to
def _create_http_basic_session
in client.py , but now I just get another error. So problem not solved. Now I get a different error:
HTTP Status 415 - Unsupported Media Type
type Status report
message Unsupported Media Type
description The server refused this request because the request entity is in
a format not` `supported by the requested resource for the requested method
(Unsupported Media Type).
So then I decided to do a super simple test just using the requests module, which I believe is being used by the jira-python module and this code seemed to log me in. I got a good response:
import requests
r = requests.get(the_url, auth=(my username , password))
print r.text
Any suggestions?
Here's how I use the jira module with authentication in a Python script:
from jira.client import JIRA
import logging
# Defines a function for connecting to Jira
def connect_jira(log, jira_server, jira_user, jira_password):
'''
Connect to JIRA. Return None on error
'''
try:
log.info("Connecting to JIRA: %s" % jira_server)
jira_options = {'server': jira_server}
jira = JIRA(options=jira_options, basic_auth=(jira_user, jira_password))
# ^--- Note the tuple
return jira
except Exception,e:
log.error("Failed to connect to JIRA: %s" % e)
return None
# create logger
log = logging.getLogger(__name__)
# NOTE: You put your login details in the function call connect_jira(..) below!
# create a connection object, jc
jc = connect_jira(log, "https://myjira.mydom.com", "myusername", "mypassword")
# print names of all projects
projects = jc.projects()
for v in projects:
print v
Below Python script connects to Jira and does basic authentication and lists all projects.
from jira.client import JIRA
options = {'server': 'Jira-URL'}
jira = JIRA(options, basic_auth=('username', 'password'))
projects = jira.projects()
for v in projects:
print v
It prints a list of all the project's available within your instance of Jira.
Problem:
As of June 2019, Atlassian Cloud users who are using a REST endpoint in Jira or Confluence Cloud with basic or cookie-based authentication will need to update their app or integration processes to use an API token, OAuth, or Atlassian Connect.
After June 5th, 2019 attempts to authenticate via basic auth with an Atlassian account password will return an invalid credentials error.
Reference: Deprecation of basic authentication with passwords for Jira and Confluence APIs
Solution to the Above-mentioned Problem:
You can use an API token to authenticate a script or other process with an Atlassian cloud product. You generate the token from your Atlassian account, then copy and paste it to the script.
If you use two-step verification to authenticate, your script will need to use a REST API token to authenticate.
Steps to Create an API Token from your Atlassian Account:
Log in to https://id.atlassian.com/manage/api-tokens
Click Create API token.
From the dialog that appears, enter a memorable and concise Label for your token and click Create.
Click Copy to clipboard, then paste the token to your script.
Reference: API tokens
Python 3.8 Code Reference
from jira.client import JIRA
jira_client = JIRA(options={'server': JIRA_URL}, basic_auth=(JIRA_USERNAME, JIRA_TOKEN))
issue = jira_client.issue('PLAT-8742')
print(issue.fields.summary)
Don't change the library, instead put your credentials inside the ~/.netrc file.
If you put them there you will also be able to test your calls using curl or wget.
I am not sure anymore about compatibility with Jira 5.x, only 7.x and 6.4 are currently tested. If you setup an instance for testing I could modify the integration tests to run against it, too.
My lucky guess is that you broke it with that change.
As of 2019 Atlassian has deprecated authorizing with passwords.
You can easily replace the password with an API Token created here.
Here's a minimalistic example:
pip install jira
from jira import JIRA
jira = JIRA("YOUR-JIRA-URL", basic_auth=("YOUR-EMAIL", "YOUR-API-TOKEN"))
issue = jira.issue("YOUR-ISSUE-KEY (e.g. ABC-13)")
print(issue.fields.summary)
I recommend storing your API Token as an environment variable and accessing it with os.environ[key].