RethinkDB connect AttributeError - python

I'm trying to make a wrapper module for the RethinkDB API and I've come across an AttributeError when importing my class(called rethinkdb.py). I'm working in a virtual machine having a shared folder 'Github'.
I do this in IPython console:
import library.api.rethinkdb as re
This is the error:
Traceback (most recent call last):
File "", line 1, in
import library.api.rethinkdb as re
File "/media/sf_GitHub/library/api/rethinkdb.py", line 51,
in
conn = Connection().connect_to_database()
File "/media/sf_GitHub/library/api/rethinkdb.py", line 48,
in connect_to_database
raise e
AttributeError: 'module' object has no attribute 'connect'
This is the code:
import rethinkdb as r #The downloaded RethinkDB module from http://rethinkdb.com/
class Connection(object):
def __init__(self, host='127.0.0.1', port=28015, database=None, authentication_key=''):
self.host = host
self.port = port
if database is None:
self.db = 'test'
self.auth_key = authentication_key
def connect_to_database(self):
try:
conn = r.connect(self.host, self.port, self.db, self.auth_key)
except Exception, e:
raise e
return conn
conn = Connection().connect_to_database()

I ran into something similar today and I noticed the authors have changed basic behavior of the API in the later versions.
From what I have tested on my machine:
v2.3.0
import rethinkdb as r
r.connect()
v2.4.1
import rethinkdb as r
rdb = r.RethinkDB()
rdb.connect()

It worked for me when I ran:
import rethinkdb as rdb
r = rdb.RethinkDB()
r.connect('localhost', 28015).repl()

Related

Python grpc: AttributeError 'NoneType' object has no attribute 'unary_unary'

My first time playing around with Python and grpc. I have been troubleshooting for a while now and cant seem to get past the below issue.
I am getting the following error by running: venv/bin/python placeholder.py (excuse the file name Im still sandboxing).
Error:
Traceback (most recent call last):
File "placeholder.py", line 50, in <module>
client = BitcClient()
File "placeholder.py", line 20, in __init__
self.stub = pb2_grpc.BranchesStub(self.channel)
File "/Users/me/PycharmProjects/app/infrastructure/v3/branches_pb2_grpc.py", line 18, in __init__
self.ListBranches = channel.unary_unary(
AttributeError: 'NoneType' object has no attribute 'unary_unary'
Here are the specs of my setup:
Specs:
certifi==2022.6.15
charset-normalizer==2.1.1
grpcio==1.39.0
grpcio-tools==1.39.0
idna==3.3
protobuf==3.20.1
requests==2.28.1
six==1.16.0
urllib3==1.26.12
(venv) % venv/bin/python --version
Python 3.8.9
Here is my client code. The server code I do not have access to as it is built by another team.
Client code:
import grpc
import app.infrastructure.v3.branches_pb2 as pb2
import app.infrastructure.v3.branches_pb2_grpc as pb2_grpc
class Client(object):
def __init__(self):
self.server = 'api.domain.com:443'
# instantiate a channel
self.channel = grpc.insecure_channel('{}'.format(self.server))
self.channel = grpc.channel_ready_future(self.channel).result(timeout=3)
# bind the client and the server
self.stub = pb2_grpc.BranchesStub(self.channel)
def get_branches(self, message):
message = pb2.ListBranchesResponse(message=message)
print(f'{message}')
return self.stub.ListBranches(message)
if __name__ == '__main__':
api_client = Client()
result = api_client()
Below is relevant code that was generated from .proto files:
Proto generated code:
class BranchesStub(object):
"""Operations to manage branches and their releation to projects.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.ListBranches = channel.unary_unary(
'/app.infrastructure.v3.Branches/ListBranches',
request_serializer=dot_app_dot_infrastructure_dot_v3_dot_branches__pb2.ListBranchesRequest.SerializeToString,
response_deserializer=dot_app_dot_infrastructure_dot_v3_dot_branches__pb2.ListBranchesResponse.FromString,
)
...
class BranchesServicer(object):
"""Operations to manage branches and their releation to Console projects.
"""
def ListBranches(self, request, context):
"""List all created branches (and their status) for the specified project
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
Help would be greatly appreciated!
Turns out issue was caused by this line:
self.channel = grpc.channel_ready_future(self.channel).result(timeout=3)
This line worked when I used it during another unrelated client.py file. Not sure why its failing now but at least my code seems to work now after removing it.

Python - AttributeError: module 'mysql' has no attribute 'connector'

I am newbie in case of python, i am using python 3.6 and mysql connecter from mysql website
pip install --allow-external mysql-connector-python mysql-connector-python
Everything was going good. I tried 3 examples from mysql website
Create DB and table , insert, select.
But after 2nd example it stops working and giving a error
Traceback (most recent call last):
File "select.py", line 3, in <module>
import mysql.connector
File "C:\Users\preet\AppData\Local\Programs\Python\Python36\lib\site-packages\
mysql\connector\__init__.py", line 37, in <module>
from .connection import MySQLConnection
File "C:\Users\preet\AppData\Local\Programs\Python\Python36\lib\site-packages\
mysql\connector\connection.py", line 45, in <module>
from .network import MySQLUnixSocket, MySQLTCPSocket
File "C:\Users\preet\AppData\Local\Programs\Python\Python36\lib\site-packages\
mysql\connector\network.py", line 28, in <module>
import socket
File "C:\Users\preet\AppData\Local\Programs\Python\Python36\lib\socket.py", li
ne 52, in <module>
import os, sys, io, selectors
File "C:\Users\preet\AppData\Local\Programs\Python\Python36\lib\selectors.py",
line 11, in <module>
import select
File "C:\Users\preet\Desktop\ptyhon-newspaper\select.py", line 7, in <module>
cnx = mysql.connector.connect(user='root', password='Jinqm21k',
AttributeError: module 'mysql' has no attribute 'connector'
Example code
from __future__ import print_function
from datetime import date, datetime, timedelta
import mysql.connector
cnx = mysql.connector.connect(user='root', password='****',
host='localhost',
database='worpress')
cursor = cnx.cursor()
query = ("SELECT first_name, last_name, hire_date FROM employees "
"WHERE hire_date BETWEEN %s AND %s")
hire_start = datetime.date(1999, 1, 1)
hire_end = datetime.date(1999, 12, 31)
cursor.execute(query, (hire_start, hire_end))
for (first_name, last_name, hire_date) in cursor:
print("{}, {} was hired on {:%d %b %Y}".format(
last_name, first_name, hire_date))
cursor.close()
cnx.close()
All examples stops working including create, insert, select
I unable to figure out what is wrong with it
Your issue was that mysql library was trying to import some packages which imports "select" package which was shadowed by your module "select.py". Please give an updated traceback what is not working now after renaming "select.py".
I also recommend you not to write code in the .py file itself, unless you want this code to be executed on module import. Create a routine instead and call it at __main__ section.
from __future__ import print_function
from datetime import date, datetime, timedelta
import mysql.connector
def print_employees():
cnx = mysql.connector.connect(user='root', password='Jinqm21k',
host='localhost',
database='worpress')
cursor = cnx.cursor()
...
if __name__ = '__main__':
print_employees()

kerberos authentication in python

we have a database running MSSQL 2008 and I am using below Python (2.7) code to authenticate using Kerberos.
import urllib2
from urlparse import urlparse
from socket import gethostbyaddr
from sspi import ClientAuth
from base64 import b64encode, b64decode
def getService(url):
return 'host/{}'.format(
gethostbyaddr(
urlparse(url).netloc.split(':')[0]
)[0][:-16]
)
status, buff = 1, None
c = ClientAuth('Kerberos', targetspn=getService(url))
while status != 0:
status, buff = c.authorize(buff)
tgt = b64encode(buff[0].Buffer)
authorization_header = \
("Negotiate " + tgt)
When I try this code in python console, getService can resolve the address correctly giving me
host/SQLSERVER1
but when I do status, buff = c.authorize(buff) it gives me
Traceback (most recent call last): File "", line 1, in
File "C:\python27\lib\site-packages\win32\lib\sspi.py",
line 139, in authorize
sec_buffer_out) pywintypes.error: (-2146893053, 'InitializeSecurityContext', 'The specified target is unknown or
unreachable')
Why does it say The specified target is unknown or unreachable? when I can ping it and gethostbyaddr as well ? is there anyway to resolve this ?

Connecting with Athena using Python and pyathenajdbc

I am trying to connect to AWS Athena using python. I am trying to use pyathenajdbc to achieve this task. The issue I am having is obtaining a connection. When I run the code below, I receive an error message stating it cannot find the AthenaDriver. ( java.lang.RuntimeException: Class com.amazonaws.athena.jdbc.AthenaDriver not found). I did download this file from AWS and I have confirmed it is sitting in that directory.
from mdpbi.rsi.config import *
from mdpbi.tools.functions import mdpLog
from pkg_resources import resource_string
import argparse
import os
import pyathenajdbc
import sys
SCRIPT_NAME = "Athena_Export"
ATHENA_JDBC_CLASSPATH = "/opt/amazon/athenajdbc/AthenaJDBC41-1.0.0.jar"
EXPORT_OUTFILE = "RSI_Export.txt"
EXPORT_OUTFILE_PATH = os.path.join(WORKINGDIR, EXPORT_OUTFILE)
def get_arg_parser():
"""This function returns the argument parser object to be used with this script"""
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
return parser
def main():
args = get_arg_parser().parse_args(sys.argv[1:])
logger = mdpLog(SCRIPT_NAME, LOGDIR)
SQL = resource_string("mdpbi.rsi.athena.resources", "athena.sql")
conn = pyathenajdbc.connect(
s3_staging_dir="s3://athena",
access_key=AWS_ACCESS_KEY_ID,
secret_key=AWS_SECRET_ACCESS_KEY,
region_name="us-east-1",
log_path=LOGDIR,
driver_path=ATHENA_JDBC_CLASSPATH
)
try:
with conn.cursor() as cursor:
cursor.execute(SQL)
logger.info(cursor.description)
logger.info(cursor.fetchall())
finally:
conn.close()
return 0
if __name__ == '__main__':
rtn = main()
sys.exit(rtn)
Traceback (most recent call last): File
"/usr/lib64/python2.7/runpy.py", line 174, in _run_module_as_main
"main", fname, loader, pkg_name) File "/usr/lib64/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals File "/home/ec2-user/jason_testing/mdpbi/rsi/athena/main.py", line 53,
in
rtn = main() File "/home/ec2-user/jason_testing/mdpbi/rsi/athena/main.py", line 39,
in main
driver_path=athena_jdbc_driver_path File "/opt/mdpbi/Python_Envs/2.7.10/local/lib/python2.7/dist-packages/pyathenajdbc/init.py",
line 65, in connect
driver_path, **kwargs) File "/opt/mdpbi/Python_Envs/2.7.10/local/lib/python2.7/dist-packages/pyathenajdbc/connection.py",
line 68, in init
jpype.JClass(ATHENA_DRIVER_CLASS_NAME) File "/opt/mdpbi/Python_Envs/2.7.10/lib64/python2.7/dist-packages/jpype/_jclass.py",
line 55, in JClass
raise _RUNTIMEEXCEPTION.PYEXC("Class %s not found" % name)
The JDBC driver requires Java 8. I was currently running Java 7. I was able to install another version of Java on EC2 instance.
https://tecadmin.net/install-java-8-on-centos-rhel-and-fedora/#
I had to also set the java version in my code. With these changes, the code now runs as expected.
from mdpbi.rsi.config import *
from mdpbi.tools.functions import mdpLog
from pkg_resources import resource_string
import argparse
import os
import pyathenajdbc
import sys
SCRIPT_NAME = "Athena_Export"
def get_arg_parser():
"""This function returns the argument parser object to be used with this script"""
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
return parser
def main():
args = get_arg_parser().parse_args(sys.argv[1:])
logger = mdpLog(SCRIPT_NAME, LOGDIR)
SQL = resource_string("mdpbi.rsi.athena.resources", "athena.sql")
os.environ["JAVA_HOME"] = "/opt/jdk1.8.0_121"
os.environ["JRE_HOME"] = "/opt/jdk1.8.0_121/jre"
os.environ["PATH"] = "/opt/jdk1.8.0_121/bin:/opt/jdk1.8.0_121/jre/bin"
conn = pyathenajdbc.connect(
s3_staging_dir="s3://mdpbi.data.rsi.out/",
access_key=AWS_ACCESS_KEY_ID,
secret_key=AWS_SECRET_ACCESS_KEY,
schema_name="rsi",
region_name="us-east-1"
)
try:
with conn.cursor() as cursor:
cursor.execute(SQL)
logger.info(cursor.description)
logger.info(cursor.fetchall())
finally:
conn.close()
return 0
if __name__ == '__main__':
rtn = main()
sys.exit(rtn)
Try this :
pyathenajdbc.ATHENA_JAR = ATHENA_JDBC_CLASSPATH
You won't be needing to specify the driver_path argument in the connection method

No module named v4.proto.omni

I have installed pysnmp-4.x.I am getting following error during running a SNMP program.
I am using pysnmpSE 3.5.2 now but getting same error. I found that pysnmpSE doesn't hav v4 module. I was suggested that following error should resolved if pySNMP SE 3.x is used.
Traceback (most recent call last):
File "C:\Documents and Settings\ggne0622\Desktop\Python\google-python-exercises\babynames\SimpleAgent.py", line 18, in <module>
from twistedsnmp import agent, agentprotocol, bisectoidstore
File "C:\Python27\Lib\site-packages\twistedsnmp\agent.py", line 4, in <module>
from twistedsnmp import datatypes
File "C:\Python27\Lib\site-packages\twistedsnmp\datatypes.py", line 7, in <module>
from twistedsnmp.pysnmpproto import v2c,v1
File "C:\Python27\Lib\site-packages\twistedsnmp\pysnmpproto.py", line 13, in <module>
from pysnmp.v4.proto.omni import v2c,v1, error, rfc1157, rfc1905
ImportError: No module named v4.proto.omni
Code:
#!/usr/bin/env python
from twisted.internet.iocpreactor import reactor
from twisted.internet import error as twisted_error
from twistedsnmp import agent, agentprotocol, bisectoidstore
#from twisted.internet import interfaces
try:
from twistedsnmp import bsdoidstore
except ImportError:
import warnings
warnings.warn( """No BSDDB OID Storage available for testing""" )
bsdoidstore = None
def createAgent( oids ):
ports = [161]+range(20000,25000)
for port in ports:
try:
`agentObject = reactor.IOCPReactor.listenUDP(port,` `agentprotocol.AgentProtocol(snmpVersion = 'v2c',agent = agent.Agent(dataStore =` `bisectoidstore.BisectOIDStore(OIDs = oids,),),),)`
`except twisted_error.CannotListenError:`
`pass`
`else:`
`return agentObject, port`
testingOIDs = {
'.1.3.6.1.2.1.1.1.0': 'Some tool out in the field',
'.1.3.6.1.2.1.1.2.0': '.1.3.6.1.4.1.88.3.1',
'.1.3.6.1.2.1.1.3.0': 558566090,
'.1.3.6.1.2.1.1.4.0': "support#somewhere.ca",
'.1.3.6.1.2.1.1.5.0': "NameOfSystem",
'.1.3.6.1.2.1.1.6.0': "SomeHeadEnd, West Hinterlands, Canada",
}
def main(oids=testingOIDs):
agent, port = createAgent( oids )
if __name__ == "__main__":
reactor.IOCPReactor.callWhenRunning( main )
reactor.IOCPReactor.run()
TwistedSNMP does not seem to be designed to work with PySNMP 4.x. Thus you should either use PySNMP 3.x / PySNMP SE or switch to PySNMP 4.x which has its own Twisted binding.

Categories