I am having an issue creating a Reddit session via my script for a bot. I have installed praw via pip and have created a praw.ini file in the same directory as my bot script:
[DEFAULT]
# A boolean to indicate whether or not to check for package updates.
check_for_updates=True
# Object to kind mappings
comment_kind=t1
message_kind=t4
redditor_kind=t2
submission_kind=t3
subreddit_kind=t5
# The URL prefix for OAuth-related requests.
oauth_url=https://oauth.reddit.com
# The URL prefix for regular requests.
reddit_url=https://www.reddit.com
# The URL prefix for short URLs.
short_url=https://redd.it
[bot1]
client_id=clientId
client_secret=clientSecret
password=myPassword
username=myUsername
user_agent=My bot description
I have verified the praw.ini file is using the correct client ID/secret. I've also upgraded to Python 2.7.14 to see if that resolves any errors as well, but when I run the following script:
import praw
reddit = praw.Reddit('bot1')
print(reddit.user.me())
I receive the following error:
Traceback (most recent call last):
File "myBot.py", line 21, in <module>
print(reddit.user.me())
File "c:\Python27\lib\site-packages\praw\models\user.py", line 60, in me
user_data = self._reddit.get(API_PATH['me'])
File "c:\Python27\lib\site-packages\praw\reddit.py", line 367, in get
data = self.request('GET', path, params=params)
File "c:\Python27\lib\site-packages\praw\reddit.py", line 472, in request
params=params)
File "c:\Python27\lib\site-packages\prawcore\sessions.py", line 181, in reques
t
params=params, url=url)
File "c:\Python27\lib\site-packages\prawcore\sessions.py", line 124, in _reque
st_with_retries
retries, saved_exception, url)
File "c:\Python27\lib\site-packages\prawcore\sessions.py", line 90, in _do_ret
ry
params=params, url=url, retries=retries - 1)
File "c:\Python27\lib\site-packages\prawcore\sessions.py", line 124, in _reque
st_with_retries
retries, saved_exception, url)
File "c:\Python27\lib\site-packages\prawcore\sessions.py", line 90, in _do_ret
ry
params=params, url=url, retries=retries - 1)
File "c:\Python27\lib\site-packages\prawcore\sessions.py", line 112, in _reque
st_with_retries
data, files, json, method, params, retries, url)
File "c:\Python27\lib\site-packages\prawcore\sessions.py", line 97, in _make_r
equest
params=params)
File "c:\Python27\lib\site-packages\prawcore\rate_limit.py", line 32, in call
kwargs['headers'] = set_header_callback()
File "c:\Python27\lib\site-packages\prawcore\sessions.py", line 141, in _set_h
eader_callback
self._authorizer.refresh()
File "c:\Python27\lib\site-packages\prawcore\auth.py", line 328, in refresh
password=self._password)
File "c:\Python27\lib\site-packages\prawcore\auth.py", line 138, in _request_t
oken
response = self._authenticator._post(url, **data)
File "c:\Python27\lib\site-packages\prawcore\auth.py", line 29, in _post
data=sorted(data.items()))
File "c:\Python27\lib\site-packages\prawcore\requestor.py", line 49, in reques
t
raise RequestException(exc, args, kwargs)
prawcore.exceptions.RequestException: error with request ("bad handshake: Error(
[('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')
],)",)
Posts on Stack Overflow that are seemingly related indicate that it is a problem with the authentication for my script, but after verifying that I'm using the correct credentials and regenerating the client ID and secret I'm still not getting past this. Does anyone have any ideas?
Seems to have been an issue with my installation of Python. I fixed this by running pip install python-certifi-win32.
Related
(I used a translator when writing this article. Please understand that some words may be incorrect.)
I tested it using the requests module. If the site cannot be found, a 404 code should be returned, but with an error. I don't know what the reason is. Any help would be appreciated. How to properly return a 404 code?
---Below is the code.
import requests as re
a = re.get(input())
print(a.status_code)
error :
Traceback (most recent call last):
File "", line 1, in
File "C:\Users\82104_dvfqr9f\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\api.py", line 75, in get
return request('get', url, params=params, **kwargs)
File "C:\Users\82104_dvfqr9f\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Users\82104_dvfqr9f\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\sessions.py", line 515, in request
prep = self.prepare_request(req)
File "C:\Users\82104_dvfqr9f\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\sessions.py", line 443, in prepare_request
p.prepare(
File "C:\Users\82104_dvfqr9f\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 318, in prepare
self.prepare_url(url, params)
File "C:\Users\82104_dvfqr9f\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 392, in prepare_url
raise MissingSchema(error)
requests.exceptions.MissingSchema: Invalid URL 'eeee.com': No scheme supplied. Perhaps you meant http://eeee.com?
You can use this link for how to work with requests module.
import requests
try:
r = requests.get('https://www.google.com/search?q=ggg')
print(r.status_code)
if r.status_code==404:
print("this url dosn't exist")
except Exception as error:
print(error)
I have the following script that grabs a repository from Github using PYGitHub
import logging
import getpass
import os
from github import Github, Repository as Repository, UnknownObjectException
GITHUB_URL = 'https://github.firstrepublic.com/api/v3'
if __name__ == '__main__':
logging.getLogger().setLevel(logging.DEBUG)
logging.debug('validating GH token')
simpleuser = getpass.getuser().replace('adm_','')
os.path.exists(os.path.join(os.path.expanduser('~' + getpass.getuser()) + '/.ssh/github-' + simpleuser + '.token'))
with open(os.path.join(os.path.expanduser('~' + getpass.getuser()) + '/.ssh/github-' + simpleuser + '.token'), 'r') as token_file:
github_token = token_file.read()
logging.debug(f'Token after file processing: {github_token}')
logging.debug('initializing github')
g = Github(base_url=GITHUB_URL, login_or_token=github_token)
logging.debug("attempting to get repository")
source_repo = g.get_repo('CLOUD/iam')
Works just fine in Python 3.9.1 on my Mac.
In production, we have RHEL7, Python 3.6.8 (can't upgrade it, don't suggest it). This is where it blows up:
(virt) user#lmachine: directory$ python3 test3.py -r ORG/repo_name -d
DEBUG:root:validating GH token
DEBUG:root:Token after file processing: <properly_formed_token>
DEBUG:root:initializing github
DEBUG:root:attempting to get repository
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): <domain>:443
Traceback (most recent call last):
File "test3.py", line 68, in <module>
source_repo = g.get_repo(args.repo)
File "/home/adm_gciesla/virt/lib/python3.6/site-packages/github/MainClass.py", line 348, in get_repo
"GET", "%s%s" % (url_base, full_name_or_id)
File "/home/user/virt/lib/python3.6/site-packages/github/Requester.py", line 319, in requestJsonAndCheck
verb, url, parameters, headers, input, self.__customConnection(url)
File "/home/user/virt/lib/python3.6/site-packages/github/Requester.py", line 410, in requestJson
return self.__requestEncode(cnx, verb, url, parameters, headers, input, encode)
File "/home/user/virt/lib/python3.6/site-packages/github/Requester.py", line 487, in __requestEncode
cnx, verb, url, requestHeaders, encoded_input
File "/home/user/virt/lib/python3.6/site-packages/github/Requester.py", line 513, in __requestRaw
response = cnx.getresponse()
File "/home/user/virt/lib/python3.6/site-packages/github/Requester.py", line 116, in getresponse
allow_redirects=False,
File "/home/user/virt/lib/python3.6/site-packages/requests/sessions.py", line 543, in get
return self.request('GET', url, **kwargs)
File "/home/user/virt/lib/python3.6/site-packages/requests/sessions.py", line 530, in request
resp = self.send(prep, **send_kwargs)
File "/home/user/virt/lib/python3.6/site-packages/requests/sessions.py", line 643, in send
r = adapter.send(request, **kwargs)
File "/home/user/virt/lib/python3.6/site-packages/requests/adapters.py", line 449, in send
timeout=timeout
File "/home/user/virt/lib/python3.6/site-packages/urllib3/connectionpool.py", line 677, in urlopen
chunked=chunked,
File "/home/user/virt/lib/python3.6/site-packages/urllib3/connectionpool.py", line 392, in _make_request
conn.request(method, url, **httplib_request_kw)
File "/usr/lib64/python3.6/http/client.py", line 1254, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/usr/lib64/python3.6/http/client.py", line 1295, in _send_request
self.putheader(hdr, value)
File "/usr/lib64/python3.6/http/client.py", line 1232, in putheader
raise ValueError('Invalid header value %r' % (values[i],))
ValueError: Invalid header value b'token <properly_formed_token>\n'
The script is a stripped down version of a larger application. I've tried rolling back to earlier versions of PyGitHub, that's really all I have control over in prod. Same error regardless. PyGithub's latest release claims Python >=3.6 should work.
I've really run the gamut of debugging. Seems like reading from environment variables can work sometimes, but the script needs to be able to use whatever credentials are available. Passing in the token as an argument is only for running locally.
Hopefully someone out there has seen something similar.
We just figured it out. Apparently, even though there's no newline in the .token file, there is one after calling file.read()
Changing github_token = token_file.read() to github_token = token_file.read().strip() fixes the problem.
I'm unable to call a SOAP request from a simple Python script in a Windows Server 2016 environment with WinPython/VSCode:
from requests import Session
from zeep import Client
from zeep.transports import Transport
wsdl = "http://www.dneonline.com/calculator.asmx?wsdl"
#wsdl = "calculator.xml"
client = Client(wsdl=wsdl)
request_data={'intA' : 1 ,
'intB' : 2}
response=client.service.Add(**request_data)
print("response: " + response)
The output I get:
Traceback (most recent call last):
File ".\zeeptest.py", line 31, in <module>
client = Client(wsdl=wsdl)
File "E:\Projects\test\zeeptest\zeeptest\lib\site-packages\zeep\client.py", line 73, in __init__
self.wsdl = Document(wsdl, self.transport, settings=self.settings)
File "E:\Projects\test\zeeptest\zeeptest\lib\site-packages\zeep\wsdl\wsdl.py", line 92, in __init__
self.load(location)
File "E:\Projects\test\zeeptest\zeeptest\lib\site-packages\zeep\wsdl\wsdl.py", line 95, in load
document = self._get_xml_document(location)
File "E:\Projects\test\zeeptest\zeeptest\lib\site-packages\zeep\wsdl\wsdl.py", line 155, in _get_xml_document
return load_external(
File "E:\Projects\test\zeeptest\zeeptest\lib\site-packages\zeep\loader.py", line 79, in load_external
content = transport.load(url)
File "E:\Projects\test\zeeptest\zeeptest\lib\site-packages\zeep\transports.py", line 122, in load
content = self._load_remote_data(url)
File "E:\Projects\test\zeeptest\zeeptest\lib\site-packages\zeep\transports.py", line 134, in _load_remote_data
response = self.session.get(url, timeout=self.load_timeout)
File "E:\Projects\test\zeeptest\zeeptest\lib\site-packages\requests\sessions.py", line 555, in get
return self.request('GET', url, **kwargs)
File "E:\Projects\test\zeeptest\zeeptest\lib\site-packages\requests\sessions.py", line 542, in request
resp = self.send(prep, **send_kwargs)
File "E:\Projects\test\zeeptest\zeeptest\lib\site-packages\requests\sessions.py", line 655, in send
r = adapter.send(request, **kwargs)
File "E:\Projects\test\zeeptest\zeeptest\lib\site-packages\requests\adapters.py", line 414, in send
raise InvalidURL(e, request=request)
requests.exceptions.InvalidURL: Not supported proxy scheme None
I tried to set the proxy manually with the following commands without success:
set http_proxy="http://<ip>:<port>"
set https_proxy="http://<ip>:<port>"
I resolved my problem by issuing the following command in a Powershell shell as an admin user:
netsh winhttp set proxy <ip>:<port>
I am having problems with Python and Bit Bucket. To display/pull/push do anything really.
I am looking # Two different libs, atlassian-python-api, and stashy, both seem to have problems my code is very simple:
from atlassian import Bitbucket
import getpass
username = input("What is your username: ")
password = getpass.getpass(prompt="Enter your password?: ")
bitbucket = Bitbucket(
url="https://website.com:port/projects/demo_projects/repppos/",
username=username,
password=password)
data = bitbucket.project_list()
both give me this error: using stashy and another library. I heard someone suggest to use Rest API but I have no experience with this?
Traceback (most recent call last):
File "C:/Users/User/PycharmProjects/ProjectName/terrafw_gui/test_no_gui.py", line 12, in <module>
data = bitbucket.project_list()
File "C:\Users\User\PycharmProjects\ProjectName\venv\lib\site-packages\atlassian\bitbucket.py", line 22, in project_list
return (self.get('rest/api/1.0/projects', params=params) or {}).get('values')
File "C:\Users\User\PycharmProjects\ProjectName\venv\lib\site-packages\atlassian\rest_client.py", line 208, in get
trailing=trailing)
File "C:\Users\User\PycharmProjects\ProjectName\venv\lib\site-packages\atlassian\rest_client.py", line 151, in request
files=files
File "C:\Users\User\PycharmProjects\ProjectName\venv\lib\site-packages\requests\sessions.py", line 279, in request
resp = self.send(prep, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies)
File "C:\Users\User\PycharmProjects\ProjectName\venv\lib\site-packages\requests\sessions.py", line 374, in send
r = adapter.send(request, **kwargs)
File "C:\Users\User\PycharmProjects\ProjectName\venv\lib\site-packages\requests\adapters.py", line 174, in send
timeout=timeout
File "C:\Users\User\PycharmProjects\ProjectName\venv\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 417, in urlopen
conn = self._get_conn(timeout=pool_timeout)
File "C:\Users\User\PycharmProjects\ProjectName\venv\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 232, in _get_conn
return conn or self._new_conn()
File "C:\Users\User\PycharmProjects\ProjectName\venv\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 547, in _new_conn
strict=self.strict)
TypeError: __init__() got an unexpected keyword argument 'strict'
Process finished with exit code 1
I cannot figure out how come, or why I am getting these error messages without an attempted connection (the error is given immediately without any seconds for timeout).
I'm not able to make HTTP calls from python based lambda function hosted on AWS and managed through Serverless framework.
I've tried using botocore.vendored requests module but it shows deprecation warning and suggested to use the requests module itself.
url = V2_URL + '/api/analytics/validate/' + smId
headers = {
'Content-Type':'application/json',
'Authorization': token
}
response = requests.get(url, headers=headers)
print('Result: ')
print(response.content)
In Cloudwatch, I see this stack trace:
[ERROR] UnboundLocalError: local variable 'response' referenced before assignment
Traceback (most recent call last):
File "/var/task/serverless_sdk/__init__.py", line 97, in wrapped_handler
return user_handler(event, context)
File "src/authorize.py", line 21, in validate
principal_id = verify_token(whole_auth_token, event['pathParameters']['smId'])
File "src/authorize.py", line 38, in verify_token
response = requests.get(url, headers=headers)
File "/var/task/requests/api.py", line 75, in get
return request('get', url, params=params, **kwargs)
File "/var/task/requests/api.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "/var/task/requests/sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "/var/task/requests/sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "/var/task/requests/adapters.py", line 449, in send
timeout=timeout
File "/var/task/serverless_sdk/__init__.py", line 384, in wrapper
if response:
As #blhsing and #Mark A pointed out, there was a bug in version 3.1.1 of #serverless/enterprise-plugin package. Upgrading it to version 3.1.2 solved the issue for me. All I had to do was npm i -g serverless and it took care of itself.
Details of issue here: https://github.com/serverless/serverless/issues/6801