def __init__(self, iface): QDialog.__init__(self) self.setupUi(self) self.iface = iface self.dbconn = DBConn(iface) self.cmbDate.clear() self.get_dates()
def __init__(self, iface): QDialog.__init__(self) self.setupUi(self) self.iface = iface self.dbconn = DBConn(iface) self.get_attributes() self.set_importable_tables()
def __init__(self, iface): QObject.__init__(self) self.iface = iface self.dbconn = DBConn(iface) plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(plugin_dir, 'i18n', 'Historize_{}.qm'.format(locale)) if os.path.exists(locale_path): translator = QTranslator() translator.load(locale_path) QCoreApplication.installTranslator(translator) if qVersion() > '4.3.3': QCoreApplication.installTranslator(translator)
class SelectDateDialog(QDialog, Ui_SelectDate): """ Class responsible for handling the date selection. """ def __init__(self, iface): QDialog.__init__(self) self.setupUi(self) self.iface = iface self.dbconn = DBConn(iface) self.cmbDate.clear() self.get_dates() def get_dates(self): """Get all historized dates from layer""" provider = self.iface.activeLayer().dataProvider() self.uri = QgsDataSourceURI(provider.dataSourceUri()) self.conn = self.dbconn.connect_to_DB(self.uri) # self.schema = self.uri.schema() self.execute = SQLExecute(self.iface, self.iface.mainWindow(), self.uri) dateList = self.execute.retrieve_all_table_versions( self.iface.activeLayer().name(), self.uri.schema()) if not dateList: self.records = False QMessageBox.warning(self.iface.mainWindow(), self.tr(u"Error"), self.tr(u"No historized versions found!")) else: for date in dateList: self.cmbDate.addItem(str(date[0])) self.records = True @pyqtSignature("") def on_buttonBox_accepted(self): """ Run hist_tabs.version() SQL-function """ if self.records: self.execute.get_older_table_version( self.uri.schema(), self.iface.activeLayer().name(), self.cmbDate.currentText(), self.uri) @pyqtSignature("") def on_buttonBox_rejected(self): """ Close Window and DB-Connection """ self.conn.close() self.close()
# Date: 2015-04-25 # Authore: Coding5 # Purpose: python Client 端insert 呼叫 # Websit: http://www.coding5.com/works?transno=1000000019 # coding=UTF-8 from dbconn import DBConn try: dbuse = DBConn() dbuse.dbConnect() sql = "INSERT INTO coding5 (codeA) VALUES ('aaa')" dbuse.runInsert(sql) dbuse.dbClose() except: print "MySQL DB Error"
def get_streak(): user_id = user.check_auth(request.headers.get('key')) if not request.headers.get('key') or not user_id: abort(401) # return current streak for this user streak = mood.get_streak(user_id) if streak is not False: return make_response(jsonify({'streak': streak or 0})) else: abort(500) @mood_app.route(Urls.percentile, methods=['GET']) def get_percentile(): user_id = user.check_auth(request.headers.get('key')) if not request.headers.get('key') or not user_id: abort(401) # return current streak for this user percentile = mood.get_max_streak_percentile(user_id) if percentile is not False: return make_response(jsonify({'percentile': percentile or 0})) else: abort(500) if __name__ == '__main__': db = DBConn() user = User() mood = Mood() mood_app.run(debug=True, host='0.0.0.0')
# Date: 2015-04-25 # Authore: Coding5 # Purpose: python Client 端delete 呼叫 # Websit: http://www.coding5.com/works?transno=1000000019 # coding=UTF-8 from dbconn import DBConn try: dbuse = DBConn() dbuse.dbConnect() sql = "DELETE coding5 WHERE codeA = 'aaa'" dbuse.runDelete(sql) dbuse.dbClose() except: print "MySQL DB Error"
class Historize(QObject): """This class handles the initialization and calls of the menus""" def __init__(self, iface): QObject.__init__(self) self.iface = iface self.dbconn = DBConn(iface) plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(plugin_dir, 'i18n', 'Historize_{}.qm'.format(locale)) if os.path.exists(locale_path): translator = QTranslator() translator.load(locale_path) QCoreApplication.installTranslator(translator) if qVersion() > '4.3.3': QCoreApplication.installTranslator(translator) def initGui(self): self.menu = QMenu() self.menu.setTitle("Historize") self.layerMenu = QMenu() self.layerMenu.setTitle("Layer") # Create menu actions self.actionInitDB = QAction(self.tr(u"Initialize Database"), self.iface.mainWindow()) self.actionInitLayer = QAction(self.tr(u"Initialize Layer"), self.iface.mainWindow()) self.actionLayerUpdate = QAction(self.tr(u"Update Layer"), self.iface.mainWindow()) self.actionLayerLoad = QAction(self.tr(u"Load Layer"), self.iface.mainWindow()) self.actionAbout = QAction(self.tr(u"About"), self.iface.mainWindow()) # Connect menu actions self.actionInitDB.triggered.connect(self.initialize_database) self.actionInitLayer.triggered.connect(self.initialize_layer) self.actionLayerLoad.triggered.connect(self.show_load_layer_dialog) self.actionLayerUpdate.triggered.connect(self.show_update_layer_dialog) self.actionAbout.triggered.connect(self.show_about_dialog) self.iface.legendInterface().currentLayerChanged.connect( self.enable_disable_gui) # Add actions to menu self.layerMenu.addActions([ self.actionInitLayer, self.actionLayerLoad, self.actionLayerUpdate ]) self.menu.addAction(self.actionInitDB) self.menu.addMenu(self.layerMenu) self.menu.addAction(self.actionAbout) self.menu.insertSeparator(self.actionAbout) menuBar = self.iface.mainWindow().menuBar() menuBar.addMenu(self.menu) # Disable unusable actions self.actionInitDB.setEnabled(False) self.actionInitLayer.setEnabled(False) self.actionLayerUpdate.setEnabled(False) self.actionLayerLoad.setEnabled(False) def unload(self): self.menu.deleteLater() def initialize_database(self): """Use Database info from layer and run historisation.sql on it.""" selectedLayer = self.iface.activeLayer() provider = selectedLayer.dataProvider() if provider.name() != 'postgres': QMessageBox.warning( self.iface.mainWindow(), self.tr(u"Invalid Layer"), self.tr(u"Layer must be provided by postgres!")) return uri = QgsDataSourceURI(provider.dataSourceUri()) conn = self.dbconn.connect_to_DB(uri) cur = conn.cursor() if conn is False: return result = QMessageBox.warning( self.iface.mainWindow(), self.tr(u"Initialize Historisation"), self.tr(u"Initialize historisation on this layers database?"), QMessageBox.No | QMessageBox.Yes) if result == QMessageBox.Yes: sqlPath = os.path.dirname( os.path.realpath(__file__)) + '/sql/historisierung.sql' try: # Ignore first three characters # which invalidate the SQL command cur.execute(open(sqlPath, "r").read()) conn.commit() QMessageBox.warning( self.iface.mainWindow(), self.tr(u"Success"), self.tr(u"Database initialized successfully!")) except psycopg2.Error as e: conn.rollback() QMessageBox.warning( self.iface.mainWindow(), self.tr(u"Error"), self.tr(u"Couldn't initialize Database.\n" + e.message)) conn.close() self.enable_disable_gui(selectedLayer) else: return def initialize_layer(self): """Use Layer info and run init() .sql query""" selectedLayer = self.iface.activeLayer() provider = selectedLayer.dataProvider() uri = QgsDataSourceURI(provider.dataSourceUri()) conn = self.dbconn.connect_to_DB(uri) if conn is False: return result = QMessageBox.warning( self.iface.mainWindow(), self.tr(u"Initialize Layer"), self.tr(u"Are you sure you wish to proceed?"), QMessageBox.No | QMessageBox.Yes) if result == QMessageBox.Yes: # Get SQL vars hasGeometry = selectedLayer.hasGeometryType() schema = uri.schema() table = uri.table() execute = SQLExecute(self.iface, self.iface.mainWindow(), uri) success, msg = execute.Init_hist_tabs(hasGeometry, schema, table) if success: QMessageBox.warning( self.iface.mainWindow(), self.tr(u"Success"), self.tr(u"Layer successfully initialized!")) else: QMessageBox.warning(self.iface.mainWindow(), self.tr(u"Error"), self.tr(u"Initialization failed!\n" + msg)) self.enable_disable_gui(selectedLayer) else: return def show_update_layer_dialog(self): """Open ImportUpdate dialog""" self.updateDialog = ImportUpdateDialog(self.iface) self.updateDialog.show() def show_load_layer_dialog(self): """Open selectDate dialog""" self.dateDialog = SelectDateDialog(self.iface) self.dateDialog.show() def show_about_dialog(self): """Show About dialog""" self.aboutDialog = AboutDialog() self.aboutDialog.show() def enable_disable_gui(self, layer): """Enable/Disable menu options based on selected layer""" self.actionInitDB.setEnabled(False) self.layerMenu.setEnabled(False) self.actionInitLayer.setEnabled(False) self.actionLayerUpdate.setEnabled(False) self.actionLayerLoad.setEnabled(False) selectedLayer = self.iface.activeLayer() if selectedLayer: provider = layer.dataProvider() if provider.name() == "postgres": self.actionInitDB.setEnabled(True) uri = QgsDataSourceURI(provider.dataSourceUri()) execute = SQLExecute(self.iface, self.iface.mainWindow(), uri) historised = execute.check_if_historised( uri.schema(), self.iface.activeLayer().name()) db_initialized = execute.db_initialize_check(uri.schema()) if db_initialized: self.actionInitDB.setEnabled(False) self.layerMenu.setEnabled(True) else: self.layerMenu.setEnabled(False) if historised: self.actionLayerUpdate.setEnabled(True) self.actionLayerLoad.setEnabled(True) else: self.actionInitLayer.setEnabled(True)
# –– coding: utf-8 – import requests import config as conf from urllib import parse from bs4 import BeautifulSoup import json from json import dumps import time import sys from kafka import KafkaProducer import hashlib from dbconn import DBConn dbconn = DBConn() def getTimestamp(): now = time.localtime() timestamp = "%04d%02d%02d%02d%02d%02d" % (now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec) return timestamp def getCurrentDate(): now = time.localtime() timestamp = "%04d-%02d-%02d-%02d:%02d:%02d" % (now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec) return timestamp
def __init__(self, iface, mainWindow, uri): DBConn.__init__(self, iface) self.mainWindow = mainWindow self.uri = uri
# -*- coding: utf-8 -* from dbconn import DBConn import time sTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print sTime try: dbuse = DBConn() dbuse.dbConn() sql = "INSERT INTO hello (name, phone, time) VALUES ('wei', '0909', '%s')" % (sTime) dbuse.runInsert(sql) dbuse.dbClose() except: print "error"
# –– coding: utf-8 – import requests from selenium import webdriver from selenium.webdriver.common.alert import Alert import config as conf from urllib import parse from bs4 import BeautifulSoup import math import json import time import sys from dbconn import DBConn dbconn = DBConn() def getCurrentDate(): now = time.localtime() timestamp = "%04d-%02d-%02d-%02d:%02d:%02d" % (now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec) return timestamp def getTimestamp(): now = time.localtime() timestamp = "%04d%02d%02d%02d%02d%02d" % (now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec) return timestamp
# Date: 2015-04-25 # Authore: Coding5 # Purpose: python Client 端update 呼叫 # Websit: http://www.coding5.com/works?transno=1000000019 # coding=UTF-8 from dbconn import DBConn try: dbuse = DBConn() dbuse.dbConnect() sql = "UPDATE coding5 SET codeA = 'bbb' WHERE codeA = 'aaa'" dbuse.dbUpdate(sql) dbuse.dbClose() except: print "MySQL DB Error"
# –– coding: utf-8 – import requests from bs4 import BeautifulSoup import yaml import re from kafka import KafkaConsumer, TopicPartition from json import dumps, loads import json import sys from kafka import KafkaProducer import time import os import config as conf from dbconn import DBConn dbconn = DBConn() flow = '' def getCurrentDate(): now = time.localtime() timestamp = "%04d-%02d-%02d-%02d:%02d:%02d" % (now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec) return timestamp def findElements(soup, queries): for __query in queries: for __tag in __query.keys(): mAttr = __query[__tag]
def parse_args(Options): """ Handle -a, -c and -s arguments; returns them as SQL constraints """ # XXX: This should go away and everything which calls it be converted # to use SQLA properly. For now, we'll just fix it not to use # the old Pg interface though session = DBConn().session() # Process suite if Options["Suite"]: suite_ids_list = [] for suitename in split_args(Options["Suite"]): suite = get_suite(suitename, session=session) if not suite or suite.suite_id is None: warn("suite '%s' not recognised." % (suite and suite.suite_name or suitename)) else: suite_ids_list.append(suite.suite_id) if suite_ids_list: con_suites = "AND su.id IN (%s)" % ", ".join([ str(i) for i in suite_ids_list ]) else: fubar("No valid suite given.") else: con_suites = "" # Process component if Options["Component"]: component_ids_list = [] for componentname in split_args(Options["Component"]): component = get_component(componentname, session=session) if component is None: warn("component '%s' not recognised." % (componentname)) else: component_ids_list.append(component.component_id) if component_ids_list: con_components = "AND c.id IN (%s)" % ", ".join([ str(i) for i in component_ids_list ]) else: fubar("No valid component given.") else: con_components = "" # Process architecture con_architectures = "" check_source = 0 if Options["Architecture"]: arch_ids_list = [] for archname in split_args(Options["Architecture"]): if archname == "source": check_source = 1 else: arch = get_architecture(archname, session=session) if arch is None: warn("architecture '%s' not recognised." % (archname)) else: arch_ids_list.append(arch.arch_id) if arch_ids_list: con_architectures = "AND a.id IN (%s)" % ", ".join([ str(i) for i in arch_ids_list ]) else: if not check_source: fubar("No valid architecture given.") else: check_source = 1 return (con_suites, con_architectures, con_components, check_source)
# -*- coding: utf-8 -* from dbconn import DBConn try: dbuse = DBConn() dbuse.dbConn() sql = "UPDATE hello SET name='imChange' WHERE id='1'" dbuse.runUpdate(sql) dbuse.dbClose() except: print "erreor"
# -*- coding: utf-8 -*- from dbconn import DBConn try: dbuse = DBConn() dbuse.dbConn() sql = "SELECT id, name, phone FROM hello" dbuse.runQuery(sql) for record in dbuse.results: col0 = record[0] col1 = record[1] col2 = record[2] print "%s, %s, %s" % (col0, col1, col2) dbuse.dbClose() except: print 'error'
# -*- coding: utf-8 -* from dbconn import DBConn try: dbuse = DBConn() dbuse.dbConn() sql = "TRUNCATE TABLE s_elect " dbuse.runTrun(sql) dbuse.dbClose() except: print "erreor"
# Date: 2015-04-23 # Authore: Coding5 # Purpose: python 物件化DB 連線client 端呼叫 # Websit: http://www.coding5.com/works?transno=1000000018 # coding=UTF-8 from dbconn import DBConn try: dbuse = DBConn() dbuse.dbConnect() sql = "SELECT codeA FROM coding5" dbuse.runQuery(sql) for record in dbuse.results: codeA = record[0] print "%s" % (codeA) dbuse.dbClose() except: print "MySQL DB Error"