django views urllib2.py https error twilio api - python

I'm looking to send an SMS with the Twilio api, but I'm getting the following error:
"unknown url type: https"
I've recompiled python with Openssl, so my code runs fine from the python interpretor, but whenever I try to run it in one of my django views I get this error. Here is my code from my view:
def send_sms(request):
recipient = '1234567890'
account = twilio.Account(settings.TWILIO_ID, settings.TWILIO_TOKEN)
params = { 'From': settings.TWILIO_NUM, 'To': recipient, 'Body': 'This is a test message.', }
account.request('/%s/Accounts/%s/SMS/Messages' % (settings.TWILIO_API_VERSION, settings.TWILIO_ID), 'POST', params)
Edit- More info (thanks for bringing that up Stefan)
The project is hosted on dreamhost via Passenger wsgi. Django is using the same python install location and interp.
I appreciate any insight anyone may have, thanks!

Looks like it was just user error. My wsgi file was using a different interpreter but the paths were so similar I was just over looking it. Once I fixed that django was using the python version that I compiled with openssl and everything worked fine.
Always check if the tv is plugged in before you take it apart. Thanks stefanw!

Related

Connecting to SharePoint with Certificate Authentication using Python

I am trying to connect to SharePoint Online using Python using Certificate Authentication using https://github.com/vgrem/Office365-REST-Python-Client
If I connect to the root of my SharePoint, it works. But if I try to connect to any specific site, it gets an error. But both work through PowerShell. So I don't think this is a setup issue.
Example - this is PowerShell using the cert in a .pfx file, connecting to the root (https://mytenant.sharepoint.com)
Connect-PnPOnline -Url https://mytenant.sharepoint.com -Tenant mytenant.onmicrosoft.com -ClientId 5fa2148c-d484-444a-bcf1-db632a0fed71 -CertificatePath 'PowershellPnp.pfx' -CertificatePassword $(ConvertTo-Securestring -string "MyCertPassword" -AsPlainText -Force)
Now I change it to connect to a specific site: https://mytenant.sharepoint.com/sites/MySite
Connect-PnPOnline -Url https://mytenant.sharepoint.com/sites/MySite -Tenant mytenant.onmicrosoft.com -ClientId 5fa2148c-d484-444a-bcf1-db632a0fed71 -CertificatePath 'PowershellPnp.pfx' -CertificatePassword $(ConvertTo-Securestring -string "MyCertPassword" -AsPlainText -Force)
Still works, no errors.
Now I try to do the same thing through Python. I use openssl to convert the .pfx to a .pem file, which is what the Python library wants.
First I try the root https://mytenant.sharepoint.com
site_url = "https://mytenant.sharepoint.com"
cert_settings = {
'client_id': '5fa2148c-d484-444a-bcf1-db632a0fed71',
'thumbprint': "D1656C4AAC5CFBB971477230A5FBACCD356829D3",
'cert_path': 'PowershellPnP.pem'
}
ctx = ClientContext(site_url).with_client_certificate('mytenant.onmicrosoft.com',**cert_settings)
This connects without error.
However, if I change the site to https://mytenant.sharepoint.com/MySite:
site_url = "https://mytenant.sharepoint.com/sites/MySite"
cert_settings = {
'client_id': '5fa2148c-d484-444a-bcf1-db632a0fed71',
'thumbprint': "D1656C4AAC5CFBB971477230A5FBACCD356829D3",
'cert_path': 'PowershellPnP.pem'
}
ctx = ClientContext(site_url).with_client_certificate('mytenant.onmicrosoft.com',**cert_settings)
I get this error:
ValueError: {'error': 'invalid_resource', 'error_description':
'AADSTS500011: The resource principal named
https://mytenant.sharepoint.com/sites/MySite was not found in the
tenant named mytenant. This can happen if the application has not been
installed by the administrator of the tenant or consented to by any
user in the tenant. You might have sent your authentication request to
the wrong tenant
I might consider what that error says, but I can connect to that site using the certificate method through PowerShell. So there should be no problem or other requirements to connect to it through Python, no?
It's not the wrong tenant, and Azure shows everything is consented. And it all works in PowersShell.
Turns out this was a bug in the library.
A workaround until it is fixed is to add a value for the scope parameter:
'scopes': ['https://{tenant}.sharepoint.com/.default']

Connecting to jira cloud using python

I am trying to connect jira cloud using REST API. This is my Python code for it:
pip install jira
from jira import JIRA
jiraOptions = {'server': "https:url"}
user = 'emailid'
apikey = 'api token'
server = 'https:url'
options = {
'server': server
}
After this when I execute this line I get a connection error
jira = JIRA(basic_auth=(user,apikey))
ConnectionRefusedError
I am not sure what has gone wrong and I tried finding the right syntax but I dont see what the problem is can anyone please help?
Hey #Bobby I ran into some similar problems. I created this repo to use straight Python and the API to get most things done - https://github.com/dren79/JiraScripting_public
A lot of the basic functionality is in the helpers.py file, let me know if it helps.

"Failed RTM connect" error when trying to connect to Slack with RTM API

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.

Trying to access database from my local server

I want to access a database from Zoho Creator using their REST API (https://www.zoho.com/creator/help/api/rest-api/rest-api-add-records.html) I read that I cannot do that from the client side (because CORS isnt implemented or something along those lines) and that I would have to do it from a server.
So I setup a local server using django and I ran a script from the terminal that should add a record to my zoho database, but it doesnt work...
I'm not sure if the script is wrong or if the way I use the server is wrong.
The server is ran by django, I made a simple server with the command "django-admin startproject mysite" and ran the server with "python manage.py runserver".
The name of the app is "synonyms-database", the form is "Main_Form" and the only field there is is called "name". So with that info I followed the API instructions and this is my script:
import requests
payload = {'authtoken': myAPIToken, 'scope': 'creatorapi', 'name': 'test'}
response = requests.request('POST',
'https://creator.zoho.com/api/erik341/json/synonyms-
database/form/Main_Form/record/add/', json=payload)
print(response.headers)
print(response.text)
print(response.url)
And I get this response:
<body>
<div>
An error has occurred. It has been reported to Zoho Creator
support. We will look into this issue .<br> Sorry for the
inconvenience caused.
<p><p>
Go to <a href='%2F'>Home</a>
</div>
</body>
If instead of json=payload I use data=payload the response changes to:
{"code":2945,"message":"INVALID_TICKET"}
The API expects form-encoded data so you should use data=payload instead of json=payload. The json in the URL is the format for the response format, not the request.
You might be able to solve the INVALID_TICKET error by regenerating the token. There's a comment on this post which solved the error by changing the URL from .eu to .com. Make sure that you generate the auth token on a URL that matches your request URL.

appengine improperly configured database error when trying to send mail (using django_bootstrap)

I am using django_bootstrap.py there are similar errors but i could not find solution to it. I am using django helper(please do not suggest non-rel)
What i was trying to do was, inside a static html js website attaching a feature of sending mail, through a contact form. The form would take the data, and jQuery would validate and make a POST AJAX request to the url "/sendmail/" the views.py i have the following code:
def sendmail(request):
logging.info("here1")
msg = request.POST['comment']; sub = request.POST['subject']
name = request.POST['name']; frm = request.POST['email']
sender = name + " " + frm
logging.info(sender)
a = mail.send_mail(sender=sender,
to="to#example.com",
subject=sub,
body=msg)
logging.info(request)
logging.info(a)
return http.HttpResponse("1")
I get absolutely no error when i remove the line:
a = mail.send_mail(sender=sender,
to="to#example.com",
subject=sub,
body=msg)
However with that line being there, i get the following error:
<class 'django.core.exceptions.ImproperlyConfigured'>: You haven't set the DATABASE_ENGINE setting yet.
I look at my settings.py file and try making some changes:
1 adding two lines as done in django-nonrel settings.py
DATABASES['native'] = DATABASES['default']
DATABASES['default'] = {'ENGINE': 'dbindexer', 'TARGET': 'native'}
This gave a 500 error on server and the page did not open.
2 I tried putting
DATABASE_ENGINE = 'dummy'
This works locally but doesnot work on server(appspot).
3 I tried putting
DATABASE_ENGINE = 'appengine'
This too gives a 500 error.
Please let me know how to solve it.
This looks messed up in all sorts of ways. Don't use bootstrap.py, it looks outdated as it's trying to load django 0.96. GAE now supports django 1.3.
Please don't use the django helper. It's not being maintained or supported by anyone. If you have problems with it, the solution is to upgrade to nonrel.
I recommend installing django-nonrel properly. Keep in mind django-nonrel is a full replacement of django. Most of it's the same, but some parts are modified to work with appengine backends. You cannot take pieces of django-nonrel and expect it to work with normal django, without a fair bit of hackery. The DATABASES lines in the settings file will only work with django-nonrel.
http://www.allbuttonspressed.com/projects/djangoappengine
Django helper doesn't have an email backend that uses appengine's email API. That's available in Django-nonrel's djangoappengine package.
If you are not using a database in your application, you can set DATABASES = {} in your settings.py file. This will fix the problem "You haven't set the DATABASE_ENGINE setting yet".

Categories