I have one class, which is reading data from a JSON file:
import os
import json
from db_connection import DB_Connection
class RA_Admin:
def __init__(self):
data = None
self.load_access_data()
def load_access_data(self):
with open('../docs/db_data.json') as data_file:
self.data = json.load(data_file)
a = RA_Admin()
db_con = DB_Connection(a.data)
db_con.read_data()
I wrote a second class to connect to a database:
import mysql.connector
class DB_Connection:
def __init__(self, data):
database_connection = None
cursor = None
user = data["database"]["user"]
paw = data["database"]["paw"]
ip_address = data["database"]["ip_adress"]
db_name = data["database"]["database_name"]
port = data["database"]["port"]
def read_data(self):
database_connection = mysql.connector.connect(user = self.user, password = self.paw, host=self.ip_address, port=self.port, database=self.db_name)
self.cursor = database_connection.cursor(dictionary=True)
I get the following error:
database_connection = mysql.connector.connect(user = self.user, password = self.paw, host=self.ip_address, port=self.port, database=self.db_name)
AttributeError: DB_Connection instance has no attribute 'user'
I can print the user in the __init__ method and the other attributes, but why are they not used in read_data?
You need self:
self.user = data["database"]["user"]
self.paw = data["database"]["paw"]
....
what-is-the-purpose-of-self-in-python
Related
I don't understand how to setup the user and password for authentication of my soap server.
I found this example:
import logging
import random
import sys
# bcrypt seems to be among the latest consensus around cryptograpic circles on
# storing passwords.
# You need the package from http://code.google.com/p/py-bcrypt/
# You can install it by running easy_install py-bcrypt.
try:
import bcrypt
except ImportError:
print('easy_install --user py-bcrypt to get it.')
raise
from spyne.application import Application
from spyne.decorator import rpc
from spyne.error import ArgumentError
from spyne.model.complex import ComplexModel
from spyne.model.fault import Fault
from spyne.model.primitive import Mandatory
from spyne.model.primitive import String
from spyne.protocol.soap import Soap11
from spyne.server.wsgi import WsgiApplication
from spyne.service import Service
class PublicKeyError(Fault):
__namespace__ = 'spyne.examples.authentication'
def __init__(self, value):
super(PublicKeyError, self).__init__(
faultstring='Value %r not found' % value)
class AuthenticationError(Fault):
__namespace__ = 'spyne.examples.authentication'
def __init__(self, user_name):
# TODO: self.transport.http.resp_code = HTTP_401
super(AuthenticationError, self).__init__(
faultcode='Client.AuthenticationError',
faultstring='Invalid authentication request for %r' % user_name)
class AuthorizationError(Fault):
__namespace__ = 'spyne.examples.authentication'
def __init__(self):
# TODO: self.transport.http.resp_code = HTTP_401
super(AuthorizationError, self).__init__(
faultcode='Client.AuthorizationError',
faultstring='You are not authozied to access this resource.')
class SpyneDict(dict):
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
raise PublicKeyError(key)
class RequestHeader(ComplexModel):
__namespace__ = 'spyne.examples.authentication'
session_id = Mandatory.String
user_name = Mandatory.String
class Preferences(ComplexModel):
__namespace__ = 'spyne.examples.authentication'
language = String(max_len=2)
time_zone = String
user_db = {
'neo': bcrypt.hashpw('Wh1teR#bbit', bcrypt.gensalt()),
}
session_db = set()
preferences_db = SpyneDict({
'neo': Preferences(language='en', time_zone='Underground/Zion'),
'smith': Preferences(language='xx', time_zone='Matrix/Core'),
})
class AuthenticationService(Service):
__tns__ = 'spyne.examples.authentication'
#rpc(Mandatory.String, Mandatory.String, _returns=String,
_throws=AuthenticationError)
def authenticate(ctx, user_name, password):
password_hash = user_db.get(user_name, None)
if password_hash is None:
raise AuthenticationError(user_name)
if bcrypt.hashpw(password, password_hash) == password_hash:
session_id = (user_name,
'%x' % random.randint(1 << 124, (1 << 128) - 1))
session_db.add(session_id)
else:
raise AuthenticationError(user_name)
return session_id[1]
class UserService(Service):
__tns__ = 'spyne.examples.authentication'
__in_header__ = RequestHeader
#rpc(Mandatory.String, _throws=PublicKeyError, _returns=Preferences)
def get_preferences(ctx, user_name):
if user_name == 'smith':
raise AuthorizationError()
retval = preferences_db[user_name]
return retval
def _on_method_call(ctx):
if ctx.in_object is None:
raise ArgumentError("RequestHeader is null")
if not (ctx.in_header.user_name, ctx.in_header.session_id) in session_db:
raise AuthenticationError(ctx.in_object.user_name)
UserService.event_manager.add_listener('method_call', _on_method_call)
if __name__ == '__main__':
from spyne.util.wsgi_wrapper import run_twisted
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG)
logging.getLogger('twisted').setLevel(logging.DEBUG)
application = Application([AuthenticationService, UserService],
tns='spyne.examples.authentication',
in_protocol=Soap11(validator='lxml'),
out_protocol=Soap11()
)
twisted_apps = [
(WsgiApplication(application), 'app'),
]
sys.exit(run_twisted(twisted_apps, 8000))
When I run this code it gives me access to files from my soap service directory. But my functions for server doesn't work anymore.
How can I configure the soap service to ask for a login and password and then give me access to the server and all the functions?
I have am using pYMYSQL to connect db and used buildozer to deploy on android device.
Can't connect to MySQL server on 'freedb.tech'
ERROR
05-14 17:15:20.090 4020 4058 org.test.myapp I python Something went
wrong: (2003, "Can't connect to MySQL server on 'freedb.tech' ([Errno
7] No address associated with hostname)")
python file
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.animation import Animation
from hoverable import HoverBehavior
from kivy.uix.image import Image
from kivy.uix.behaviors import ButtonBehavior
import json, glob
from datetime import datetime
from pathlib import Path
import random
import pymysql.cursors
db_string = "postgresql://[user]:[password]#ec2-54-197-100-79.compute-1.amazonaws.com:5432/d4bsdrtg9i2j5d"
Builder.load_file('design.kv')
class LoginScreen(Screen):
def sign_up(self):
self.manager.current = "sign_up_screen"
def login(self, uname, pword):
with open("users.json") as file:
users = json.load(file)
if uname in users and users[uname]['password'] == pword:
self.manager.current = 'login_screeen_success'
else:
anim = Animation(color=(0.6, 0.7, 0.1, 1))
anim.start(self.ids.login_wrong)
self.ids.login_wrong.text = "Wrong username or password!"
class RootWidget(ScreenManager):
pass
class SignUpScreen(Screen):
def add_user(self, uname, pword):
with open("users.json") as file:
users = json.load(file)
users[uname] = {'username': uname, 'password': pword,
'created': datetime.now().strftime("%Y-%m-%d %H-%M-%S")}
with open("users.json", 'w') as file:
json.dump(users, file)
self.manager.current = "sign_up_screen_success"
class SignUpScreenSuccess(Screen):
def go_to_login(self):
self.manager.transition.direction = 'right'
self.manager.current = "login_screen"
class LoginScreenSuccess(Screen):
def log_out(self):
self.manager.transition.direction = "right"
self.manager.current = "login_screen"
def get_quote(self, feel):
feel = feel.lower()
available_feelings = glob.glob("quotes/*txt")
available_feelings = [Path(filename).stem for filename in
available_feelings]
if feel in available_feelings:
with open(f"quotes/{feel}.txt", encoding='utf8') as file:
quotes = file.readlines()
self.ids.quote.text = random.choice(quotes)
else:
self.ids.quote.text = "Try another feeling"
def feed_back(self):
self.manager.current = "feedback_screen"
class ImageButton(ButtonBehavior, HoverBehavior, Image):
pass
class FeedbackScreen(Screen):
def send_feed(self, feed):
print(feed)
# connection = psycopg2.connect(user="[user]",
# password="[password]",
# host="ec2-54-197-100-79.compute-1.amazonaws.com",
# port="5432",
# database="d4bsdrtg9i2j5d")
# db = create_engine(db_string)
#
# postgres_insert_query = """INSERT INTO feed(feed_info) VALUES (%s)"""
#
# db.execute(postgres_insert_query, feed)
# print("Record inserted successfully into feed table")
try:
mydb = pymysql.connect(
host="freedb.tech",
user="freedbtech_reds",
password="Raskol#786",
database="freedbtech_redsdb"
)
mycursor = mydb.cursor()
sql = "INSERT INTO feed (feed_info) VALUES (%s)"
val = (feed,)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "Record inserted successfully into feed table")
self.manager.current = 'login_screen'
except pymysql.Error as err:
print("Something went wrong: {}".format(err))
class MainApp(App):
def build(self):
return RootWidget()
if __name__ == "__main__":
MainApp().run()
---------------------------------
buildozer spec
--------------------------------
requirements = python3,kivy,PyMySQL
your saying that these credentials are correct but your still can't connect to database
this is simple problem
Note:-
if you don't have internet access you get this error also
so to get internet access You have to add android.permissions = INTERNET in your buildozer.spec file
Happy coding (^_^)
I have to load some PostGIS layers with PyQGIS to QGIS projects. Until Version 3.8 of QGIS I had a working solution. The Connection is made with this code:
from qgis.core import QgsDataSourceUri, QgsVectorLayer, QgsDataSourceUri
import re
import time
import db_manager.db_plugins.postgis.connector as con
...
class PgConnection:
def __init__(self, host, dbname, port):
self.uri = QgsDataSourceUri()
self.host = host
self.dbname = dbname
self.port = port
self.authcfg = None
self.user = ''
self.passwd = ''
settings = QgsSettings()
settings.beginGroup('PostgreSQL/connections')
for connectionName in settings.childGroups():
if settings.value(f'{connectionName}/host') == host and \
settings.value(f'{connectionName}/database') == dbname:
self.authcfg = settings.value(f'{connectionName}/authcfg')
break
if self.authcfg is None:
self.uri.setConnection(self.host, port, self.dbname, None, None)
connInfo = self.uri.connectionInfo()
(success, user, passwd) = QgsCredentials.instance().get(connInfo, None, None)
if success:
self.uri.setPassword(passwd)
self.uri.setUsername(user)
else:
self.uri.setConnection(self.host, self.port, self.dbname, None, None, authConfigId=self.authcfg)
Now I need to get all tables from a specific schema. Until QGIS version 3.8 I used following code for this (in the same class):
def getPgTableNames(self, schema):
tablenames = con.PostGisDBConnector(self.uri)
return tablenames.getTables(schema)
Since version 3.10 this is not longer working as con.PostGisDBConnector(self.uri) throws an error. What is the correct way to get the tablenames?
It took a while to find my error. The above code does not establish a connection to the database. I did this later when adding layers to the project. However i had to add following line:
self.conn = QgsProviderRegistry.instance().providerMetadata('postgres').createConnection(self.uri.uri(),{})
the function to return the tablelist is now:
def getPgTableNames(self):
tablenames = self.conn.tables(self.schema)
return tablenames
And the complete code:
from qgis.core import QgsDataSourceUri, QgsVectorLayer, QgsProviderRegistry, QgsProviderMetadata
import re
import time
#Klassendefinitionen
class PgConnection:
def __init__(self, host, dbname, port, schema):
self.uri = QgsDataSourceUri()
self.host = host
self.dbname = dbname
self.port = port
self.schema = schema
self.authcfg = None
self.user = ''
self.passwd = ''
pgProvider = QgsProviderRegistry.instance().providerMetadata('postgres')
settings = QgsSettings()
settings.beginGroup('PostgreSQL/connections')
for connectionName in settings.childGroups():
if settings.value(f'{connectionName}/host') == host and \
settings.value(f'{connectionName}/database') == dbname:
self.authcfg = settings.value(f'{connectionName}/authcfg')
break
if self.authcfg is None:
self.uri.setConnection(self.host, port, self.dbname, None, None)
connInfo = self.uri.connectionInfo()
(success, user, passwd) = QgsCredentials.instance().get(connInfo, None, None)
if success:
self.uri.setPassword(passwd)
self.uri.setUsername(user)
else:
self.uri.setConnection(self.host, self.port, self.dbname, None, None, authConfigId=self.authcfg)
self.conn = QgsProviderRegistry.instance().providerMetadata('postgres').createConnection(self.uri.uri(),{})
def getPgTableNames(self):
tablenames = self.conn.tables(self.schema)
return tablenames
#Verbindungsdaten angeben
host = 'some_host'
dbname = 'some_db'
schema = 'some_schema'
port = '1234'
# Verbindung zu Postgis aufbauen
uri = PgConnection(host,dbname, port, schema)
tableList = uri.getPgTableNames()
for t in tableList:
print (t.defaultName())
I just use the connection name and it works. I have a connection named ftth and using such name, I can get the connection out of it.
conn = QgsProviderRegistry.instance().providerMetadata('postgres').createConnection('ftth')
conn.tables()
while inserting the data into mysql database, it is throwing the "MySQLdb._exceptions.OperationalError: (1046, 'No database selected')". I have checked step by step in this code snippet. database has been connected. But it is showing above error.
Here is my database created query.
create table database_conn(id int,name varchar(20),age int(100),address varchar(50),state varchar(10), zipcode int(20));
Here is my python code snippet for inserting data into database.
class Database_conn:
def __init__(self,host,user,password,database,file_name):
self.host = host
self.user = user
self.password = password
self.database = database
self.file_name = file_name
self.conn()
self.excel_sheet()
self.db_query()
def conn(self):
self.mydb = MySQLdb.connect(host=self.host,
user = self.user,password = self.password)
def excel_sheet(self):
self.book = xlrd.open_workbook(self.file_name)
self.sheet = self.book.sheet_by_name("Sheet1")
try:
self.cursor = self.mydb.cursor()
print('established cursor connection')
except:
print('something goes worng')
def db_query(self):
global values, conn
self.query = """INSERT INTO database_conn(id,name,age,address,state,zipcode)VALUES(%s,%s,%s,%s,%s,%s)"""
for i in range(1,self.sheet.nrows):
id = self.sheet.cell(i,0).value
name = self.sheet.cell(i,1).value
age = self.sheet.cell(i,2).value
address = self.sheet.cell(i,3).value
state = self.sheet.cell(i,4).value
zipcode = self.sheet.cell(i,5).value
values = (id, name, age, address, state, zipcode)
conn = self.cursor
conn.execute(self.query, values)
conn.commit()
conn.close()
file_name = input('Enter a file_name : ')
d=Database_conn('localhost','****','****','****',file_name)
In above code i am getting the error in this line
conn.execute(self.query, values)
Finally i did insert the data into my db.
Here is my Answer:
class Database_conn:
def __init__(self,host,user,password,database,file_name):
self.host = host
self.user = user
self.password = password
self.database = database
self.file_name = file_name
self.conn()
self.excel_sheet()
self.db_query()
self.db_close()
def conn(self):
self.mydb = MySQLdb.connect(host=self.host,
user = self.user,password = self.password,db=self.database)
def excel_sheet(self):
self.book = xlrd.open_workbook(self.file_name)
self.sheet = self.book.sheet_by_name("Sheet1")
try:
self.cursor = self.mydb.cursor()
print('established cursor connection')
except:
print('something goes worng')
def db_query(self):
global values, conn
self.query = """INSERT INTO database_conn(id,name,age,address,state,zipcode)VALUES(%s,%s,%s,%s,%s,%s)"""
for i in range(1,self.sheet.nrows):
id = self.sheet.cell(i,0).value
name = self.sheet.cell(i,1).value
age = self.sheet.cell(i,2).value
address = self.sheet.cell(i,3).value
state = self.sheet.cell(i,4).value
zipcode = self.sheet.cell(i,5).value
values = (id, name, age, address, state, zipcode)
conn = self.cursor
conn.execute(self.query, values)
conn.close()
def db_close(self):
self.database.commit()
self.database.commit()
file_name = input('Enter a file_name : ')
d=Database_conn('localhost','****','****','*****',file_name)
I'm trying to login to my MySQL server that I'm running on DigitalOcean, but unfortunately I have no clue as to how to push the login through python. I've got the MySQL part implemented, but don't know how to login to the actual server itself (the computer). What other code do I need to add to accomplish this? I've already added the variables mySqlUser and mySqlPassword to the top of the file.
Here is the code I have so far:
import MySQLdb
class Database:
host = 'some ip address'
user = 'root'
password = '123'
mySqlUser = 'root'
mySqlPassword = 'someotherpassword'
db = 'test'
def __init__(self):
self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db)
self.cursor = self.connection.cursor()
def insert(self, query):
try:
self.cursor.execute(query)
self.connection.commit()
except:
self.connection.rollback()
def query(self, query):
cursor = self.connection.cursor( MySQLdb.cursors.DictCursor )
cursor.execute(query)
return cursor.fetchall()
def __del__(self):
self.connection.close()
if __name__ == "__main__":
db = Database()
#CleanUp Operation
del_query = "DELETE FROM basic_python_database"
db.insert(del_query)
# Data Insert into the table
query = """
INSERT INTO basic_python_database
(`name`, `age`)
VALUES
('Mike', 21),
('Michael', 21),
('Imran', 21)
"""
# db.query(query)
db.insert(query)
# Data retrieved from the table
select_query = """
SELECT * FROM basic_python_database
WHERE age = 21
"""
people = db.query(select_query)
for person in people:
print "Found %s " % person['name']
You can Try this:
def __init__(self):
self.host = 'some ip address'
self.user = 'root'
self.password = '123'
self.mySqlUser = 'root'
self.mySqlPassword = 'someotherpassword'
self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db)
self.cursor = self.connection.cursor()
or
def __init__(self):
self.connection = MySQLdb.connect(host, user, password, db)
self.cursor = self.connection.cursor()
and you batter transfer parameter when instantiation you class , instead of fixed values in class.
just a suggest and don't mind my english (: