本文整理汇总了Python中pymysql.install_as_MySQLdb函数的典型用法代码示例。如果您正苦于以下问题:Python install_as_MySQLdb函数的具体用法?Python install_as_MySQLdb怎么用?Python install_as_MySQLdb使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了install_as_MySQLdb函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: query
def query(self, proxyType):
if 'simple' == proxyType:
link = 'http://www.baidu.com';
else:
link = 'http://www.google.com';
pymysql.install_as_MySQLdb();
output = open('misc/proxy.py', 'w');
conn = pymysql.connect(host='192.168.0.27', port=3306, user='mezhou887', passwd='Admin1234#', db='quartz');
cur = conn.cursor()
output.write('HTTPPROXIES = ['+'\n');
cur.execute("SELECT IPADDRESS, PORT FROM quartz.data_proxy where upper(type) = 'HTTP' order by dealdate desc ");
for r in cur:
if self.test(r[0]+':'+r[1], link, 'http'):
output.write('{"ip_port": "'+r[0]+':'+r[1]+'"},'+'\n');
output.writelines(']'+'\n\n');
output.write('HTTPSPROXIES = ['+'\n');
cur.execute("SELECT IPADDRESS, PORT FROM quartz.data_proxy where upper(type) = 'HTTPS' order by dealdate desc ");
for r in cur:
if self.test(r[0]+':'+r[1], link, 'https'):
output.write('{"ip_port": "'+r[0]+':'+r[1]+'"},'+'\n');
output.writelines(']'+'\n\n');
cur.close();
conn.close();
output.close();
开发者ID:mezhou887,项目名称:scrapysystem,代码行数:28,代码来源:updateproxy.py
示例2: use_pymysql
def use_pymysql():
try:
from pymysql import install_as_MySQLdb
except ImportError:
pass
else:
install_as_MySQLdb()
开发者ID:pigsoldierlu,项目名称:sheep,代码行数:7,代码来源:monkey.py
示例3: connect
def connect(self):
try:
import pymysql
pymysql.install_as_MySQLdb()
info("Using pure python SQL client")
except ImportError:
info("Using other SQL client")
try:
import MySQLdb
except ImportError:
critical("ERROR: missing a mysql python module")
critical("Install either 'PyMySQL' or 'mysqlclient' from your OS software repository or from PyPI")
raise
try:
args = {
'host': self.config.db_host,
'port': self.config.db_port,
'user': self.config.db_user,
'passwd': self.config.db_pass,
'db': self.config.db_name
}
if self.config.db_socket:
args['unix_socket'] = self.config.db_socket
conn = MySQLdb.connect(**args)
conn.autocommit(True)
conn.ping(True)
self._db[threading.get_ident()] = conn
except Exception as e:
critical("ERROR: Could not connect to MySQL database! {}".format(e))
raise
开发者ID:djamp42,项目名称:librenms,代码行数:33,代码来源:__init__.py
示例4: __init__
def __init__(self, host, username, password, dbname):
pymysql.install_as_MySQLdb()
db = 'mysql+mysqldb://' + username + ':' + password + '@' + host + '/' + dbname + '?charset=utf8'
self.engine = create_engine(db)
self.engine.connect()
self.s = Session(self.engine)
self.Base = automap_base()
self.Base.prepare(self.engine, reflect=True)
开发者ID:chackenberger,项目名称:Wahlanalyse,代码行数:8,代码来源:dbconnection.py
示例5: readUserDB_list
def readUserDB_list():
pymysql.install_as_MySQLdb()
conn = pymysql.connect(host=datahost, database=database, user=datauser, password=userpass)
mycursor = conn.cursor()
mycursor.execute('SELECT * FROM Test.Users')
result = mycursor.fetchall()
conn.close
return result
开发者ID:GeorgyGol,项目名称:Idea,代码行数:8,代码来源:test.py
示例6: __init__
def __init__(self, host, username, password, database):
# use as MYSQLdb alternative
pymysql.install_as_MySQLdb()
self.host = host
self.username = username
self.password = password
self.database = database
super().__init__()
开发者ID:sgeyer-tgm,项目名称:WahlAnalyse,代码行数:10,代码来源:database.py
示例7: readUserDB
def readUserDB():
pymysql.install_as_MySQLdb()
conn = pymysql.connect(host=datahost, database=database, user=datauser, password=userpass)
mycursor = conn.cursor()
mycursor.execute('SELECT * FROM Test.Users')
result = mycursor.fetchall()
outp=''
for (Id, Name, EMail) in result:
outp+= "Name={1}, Id={0}, EMail={2}<BR/>".format(Id, Name, EMail)
conn.close
return outp
开发者ID:GeorgyGol,项目名称:Idea,代码行数:13,代码来源:test.py
示例8: test_suite
def test_suite():
try:
# attempt to import MySQLdb
try:
import MySQLdb
except ImportError:
# use all pymysql as an alternative
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
except ImportError, e:
import warnings
warnings.warn("MySQLdb is not importable, so MySQL tests disabled")
return unittest.TestSuite()
开发者ID:c0ns0le,项目名称:zenoss-4,代码行数:14,代码来源:testmysql.py
示例9: patch_all
def patch_all():
monkey.patch_all()
if module_exists('psycogreen'):
from psycogreen.gevent.psyco_gevent import make_psycopg_green
make_psycopg_green()
if module_exists('pymysql'):
import pymysql
pymysql.install_as_MySQLdb()
if module_exists('gevent_zeromq'):
from gevent_zeromq import zmq
sys.modules["zmq"] = zmq
if module_exists('pylibmc'):
import memcache
sys.modules["pylibmc"] = memcache
开发者ID:philipn,项目名称:green-monkey,代码行数:18,代码来源:__init__.py
示例10: main
def main(argv=['', 'runserver', '0.0.0.0:8000']):
pymysql.install_as_MySQLdb()
match_file = re.compile("initial\.py$")
argv = argv if len(sys.argv) == 1 else sys.argv
base_dir = os.path.dirname(os.path.abspath(__file__))
logs_dir = os.path.join(base_dir, 'logs')
if not all([os.path.isdir(logs_dir), not os.path.isfile(logs_dir)]):
os.makedirs(logs_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "afcat.settings")
try:
from django.core.management import execute_from_command_line, call_command
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
has_migrate = False
root_dir = settings.BASE_DIR
for app in settings.INSTALLED_APPS:
app = app.split('.')[-1]
app_dir = os.path.join(root_dir, app)
if os.path.isdir(app_dir):
migrations_dir = "%s/%s" % (app_dir, "migrations")
if os.path.isdir(migrations_dir):
match = any(map(lambda initial_file: match_file.search(initial_file), os.listdir(migrations_dir)))
if not match:
if not has_migrate:
has_migrate = True
execute_from_command_line(['afcat_client.py', 'migrate','--database', 'cmdb'])
execute_from_command_line(['afcat_client.py', 'makemigrations', app])
if has_migrate:
execute_from_command_line(['afcat_client.py', 'migrate'])
execute_from_command_line(argv)
开发者ID:tonglinge,项目名称:MyProjects,代码行数:41,代码来源:manage.py
示例11: variable
import os
from fnmatch import fnmatch
from django.conf import global_settings
from varlet import variable
import pymysql
pymysql.install_as_MySQLdb()
PROJECT_DIR = os.path.dirname(__file__)
HOME_DIR = os.path.normpath(os.path.join(PROJECT_DIR, '../'))
DEBUG = variable("DEBUG", default=False)
TEMPLATE_DEBUG = DEBUG
# if you're having trouble connecting to LDAP set this to True so you can login
# to track, bypassing LDAP group checks
LDAP_DISABLED = variable("LDAP_DISABLED", default=False)
LDAP = {
'default': {
'host': "ldap://ldap-login.oit.pdx.edu",
'username': 'traq',
'password': '',
'search_dn': 'dc=pdx,dc=edu'
}
}
# ('Your Name', '[email protected]'),
ADMINS = variable("ADMINS", [])
MANAGERS = ADMINS
开发者ID:PSU-OIT-ARC,项目名称:traq,代码行数:30,代码来源:settings.py
示例12: install_project_hook
def install_project_hook():
import pymysql
pymysql.install_as_MySQLdb()
开发者ID:gzqichang,项目名称:wa,代码行数:3,代码来源:hooks.py
示例13: run
def run(base_dir, start_gunicorn_app=True):
# Store a pidfile before doing anything else
store_pidfile(base_dir)
# For dumping stacktraces
register_diag_handlers()
# Start initializing the server now
os.chdir(base_dir)
try:
import pymysql
pymysql.install_as_MySQLdb()
except ImportError:
pass
# We're doing it here even if someone doesn't use PostgreSQL at all
# so we're not suprised when someone suddenly starts using PG.
# TODO: Make sure it's registered for each of the subprocess
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)
repo_location = os.path.join(base_dir, 'config', 'repo')
# Configure the logging first, before configuring the actual server.
logging.addLevelName('TRACE1', TRACE1)
logging.config.fileConfig(os.path.join(repo_location, 'logging.conf'))
logger = logging.getLogger(__name__)
kvdb_logger = logging.getLogger('zato_kvdb')
config = get_config(repo_location, 'server.conf')
# New in 2.0 - Start monitoring as soon as possible
if config.get('newrelic', {}).get('config'):
import newrelic.agent
newrelic.agent.initialize(
config.newrelic.config, config.newrelic.environment or None, config.newrelic.ignore_errors or None,
config.newrelic.log_file or None, config.newrelic.log_level or None)
# Store KVDB config in logs, possibly replacing its password if told to
kvdb_config = get_kvdb_config_for_log(config.kvdb)
kvdb_logger.info('Master process config `%s`', kvdb_config)
# New in 2.0 hence optional
user_locale = config.misc.get('locale', None)
if user_locale:
locale.setlocale(locale.LC_ALL, user_locale)
value = 12345
logger.info('Locale is `%s`, amount of %s -> `%s`', user_locale, value,
locale.currency(value, grouping=True).decode('utf-8'))
# Spring Python
app_context = get_app_context(config)
# Makes queries against Postgres asynchronous
if asbool(config.odb.use_async_driver) and config.odb.engine == 'postgresql':
make_psycopg_green()
# New in 2.0 - Put HTTP_PROXY in os.environ.
http_proxy = config.misc.get('http_proxy', False)
if http_proxy:
os.environ['http_proxy'] = http_proxy
crypto_manager = get_crypto_manager(repo_location, app_context, config)
parallel_server = app_context.get_object('parallel_server')
zato_gunicorn_app = ZatoGunicornApplication(parallel_server, repo_location, config.main, config.crypto)
parallel_server.crypto_manager = crypto_manager
parallel_server.odb_data = config.odb
parallel_server.host = zato_gunicorn_app.zato_host
parallel_server.port = zato_gunicorn_app.zato_port
parallel_server.repo_location = repo_location
parallel_server.base_dir = base_dir
parallel_server.fs_server_config = config
parallel_server.user_config.update(config.user_config_items)
parallel_server.startup_jobs = app_context.get_object('startup_jobs')
parallel_server.app_context = app_context
# Remove all locks possibly left over by previous server instances
kvdb = app_context.get_object('kvdb')
kvdb.component = 'master-proc'
clear_locks(kvdb, config.main.token, config.kvdb, crypto_manager.decrypt)
# Turn the repo dir into an actual repository and commit any new/modified files
RepoManager(repo_location).ensure_repo_consistency()
# New in 2.0 so it's optional.
profiler_enabled = config.get('profiler', {}).get('enabled', False)
if asbool(profiler_enabled):
profiler_dir = os.path.abspath(os.path.join(base_dir, config.profiler.profiler_dir))
parallel_server.on_wsgi_request = ProfileMiddleware(
parallel_server.on_wsgi_request,
log_filename = os.path.join(profiler_dir, config.profiler.log_filename),
cachegrind_filename = os.path.join(profiler_dir, config.profiler.cachegrind_filename),
discard_first_request = config.profiler.discard_first_request,
flush_at_shutdown = config.profiler.flush_at_shutdown,
#.........这里部分代码省略.........
开发者ID:SciF0r,项目名称:zato,代码行数:101,代码来源:main.py
示例14: install_as_MySQLdb
from pymysql import install_as_MySQLdb
install_as_MySQLdb()
开发者ID:ungikim,项目名称:KAuth,代码行数:3,代码来源:__init__.py
示例15: weibo_number_analysis
#encoding=utf-8
import data
import chardet
import pymysql as MySQLdb
from matplotlib import pylab as plt
import cPickle
import numpy as np
import datetime
MySQLdb.install_as_MySQLdb()
conn = MySQLdb.connect(host='localhost', user='root',passwd='1', db = 'ped_new', charset='utf8')
cursor = conn.cursor()
def weibo_number_analysis():
initTime = datetime.datetime(2013, 04,01)
timeinfo = []
count = []
for r in xrange(0, 31):
preTime = initTime + datetime.timedelta(days = r)
nextTime = initTime + datetime.timedelta(days = r+1)
c = cursor.execute('select * from weibo_new where publish_time > "%s" and publish_time < "%s"' %(str(preTime), str(nextTime)))
print "Between %s and %s there are %s weibos" %(preTime, nextTime, c)
timeinfo.append(str(datetime.date.isoformat(preTime)))
count.append(c)
plt.xticks(range(len(timeinfo)), timeinfo, size='small', rotation='vertical')
plt.ylabel('Number of Tweet')
plt.xlabel('date')
# plt.hist(count, 50, normed=1, facecolor='g', alpha=0.75)
开发者ID:dreamingo,项目名称:emerging_topic_detection,代码行数:31,代码来源:analysis.py
示例16: __init__
def __init__(self,name="CR"):
self.app = Flask(name)
self.db = SQLAlchemy(self.app)
pm.install_as_MySQLdb()
self.app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:[email protected]/shuracr?charset=utf8'
self.db.init_app(self.app)
开发者ID:ahmedaswai,项目名称:ChangeRequest,代码行数:6,代码来源:config.py
示例17: __init__
def __init__(self, username, password, database):
pymysql.install_as_MySQLdb()
connection_string = "mysql+mysqldb://" + username + ":" + password + "@127.0.0.1/" + database + "?charset=utf8"
super().__init__(connection_string)
开发者ID:mbruckner-tgm,项目名称:CSV-Projekt,代码行数:4,代码来源:Connector.py
示例18: __init__
def __init__(self, db, user, password='', host='localhost', port=0, **kw):
drivers = kw.pop('driver', None) or 'mysqldb'
for driver in drivers.split(','):
driver = driver.strip()
if not driver:
continue
try:
if driver.lower() in ('mysqldb', 'pymysql'):
if driver.lower() == 'pymysql':
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
if driver.lower() == 'mysqldb':
if MySQLdb.version_info[:3] < (1, 2, 2):
raise ValueError(
'SQLObject requires MySQLdb 1.2.2 or later')
import MySQLdb.constants.CR
import MySQLdb.constants.ER
self.module = MySQLdb
if driver.lower() == 'mysqldb':
self.CR_SERVER_GONE_ERROR = \
MySQLdb.constants.CR.SERVER_GONE_ERROR
self.CR_SERVER_LOST = \
MySQLdb.constants.CR.SERVER_LOST
else:
self.CR_SERVER_GONE_ERROR = \
MySQLdb.constants.CR.CR_SERVER_GONE_ERROR
self.CR_SERVER_LOST = \
MySQLdb.constants.CR.CR_SERVER_LOST
self.ER_DUP_ENTRY = MySQLdb.constants.ER.DUP_ENTRY
elif driver == 'connector':
import mysql.connector
self.module = mysql.connector
self.CR_SERVER_GONE_ERROR = \
mysql.connector.errorcode.CR_SERVER_GONE_ERROR
self.CR_SERVER_LOST = \
mysql.connector.errorcode.CR_SERVER_LOST
self.ER_DUP_ENTRY = mysql.connector.errorcode.ER_DUP_ENTRY
elif driver == 'oursql':
import oursql
self.module = oursql
self.CR_SERVER_GONE_ERROR = \
oursql.errnos['CR_SERVER_GONE_ERROR']
self.CR_SERVER_LOST = oursql.errnos['CR_SERVER_LOST']
self.ER_DUP_ENTRY = oursql.errnos['ER_DUP_ENTRY']
else:
raise ValueError(
'Unknown MySQL driver "%s", '
'expected mysqldb, connector, '
'oursql or pymysql' % driver)
except ImportError:
pass
else:
break
else:
raise ImportError(
'Cannot find a MySQL driver, tried %s' % drivers)
self.host = host
self.port = port or 3306
self.db = db
self.user = user
self.password = password
self.kw = {}
for key in ("unix_socket", "init_command",
"read_default_file", "read_default_group", "conv"):
if key in kw:
self.kw[key] = kw.pop(key)
for key in ("connect_timeout", "compress", "named_pipe", "use_unicode",
"client_flag", "local_infile"):
if key in kw:
self.kw[key] = int(kw.pop(key))
for key in ("ssl_key", "ssl_cert", "ssl_ca", "ssl_capath"):
if key in kw:
if "ssl" not in self.kw:
self.kw["ssl"] = {}
self.kw["ssl"][key[4:]] = kw.pop(key)
if "charset" in kw:
self.dbEncoding = self.kw["charset"] = kw.pop("charset")
else:
self.dbEncoding = None
global mysql_Bin
if not PY2 and mysql_Bin is None:
mysql_Bin = self.module.Binary
self.module.Binary = lambda x: mysql_Bin(x).decode(
'ascii', errors='surrogateescape')
self._server_version = None
self._can_use_microseconds = None
DBAPI.__init__(self, **kw)
开发者ID:LutzSteinborn,项目名称:sqlobject,代码行数:90,代码来源:mysqlconnection.py
示例19: ImportError
# Requires PyMySql as first choice or
# MySQLdb <https://sourceforge.net/projects/mysql-python/>
try:
import pymysql as mysqldb
except ImportError:
try:
import MySQLdb as mysqldb
except ImportError:
raise ImportError('No supported MySQL library installed. '
'Please install PyMySQL.')
else:
pywikibot.warning("PyMySQL not found. It'll fallback "
'on the deprecated library MySQLdb.')
else:
mysqldb.install_as_MySQLdb()
from pywikibot import config2 as config
from pywikibot.tools import deprecated_args, UnicodeType
@deprecated_args(encoding=None)
def mysql_query(query, params=None, dbname=None, verbose=None):
"""Yield rows from a MySQL query.
An example query that yields all ns0 pages might look like::
SELECT
page_namespace,
page_title,
FROM page
开发者ID:Zeffar,项目名称:Elobot,代码行数:30,代码来源:mysql.py
示例20: run
def run(base_dir, start_gunicorn_app=True):
# Store a pidfile before doing anything else
store_pidfile(base_dir)
# For dumping stacktraces
register_diag_handlers()
# Capture warnings to log files
logging.captureWarnings(True)
# Start initializing the server now
os.chdir(base_dir)
try:
import pymysql
pymysql.install_as_MySQLdb()
except ImportError:
pass
# We're doing it here even if someone doesn't use PostgreSQL at all
# so we're not suprised when someone suddenly starts using PG.
# TODO: Make sure it's registered for each of the subprocess
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)
# We know we don't need warnings because users may explicitly configure no certificate validation.
# We don't want for urllib3 to warn us about it.
import requests as _r
_r.packages.urllib3.disable_warnings()
repo_location = os.path.join(base_dir, 'config', 'repo')
# Configure the logging first, before configuring the actual server.
logging.addLevelName('TRACE1', TRACE1)
with open(os.path.join(repo_location, 'logging.conf')) as f:
dictConfig(yaml.load(f))
logger = logging.getLogger(__name__)
kvdb_logger = logging.getLogger('zato_kvdb')
config = get_config(repo_location, 'server.conf')
# New in 2.0 - Start monitoring as soon as possible
if config.get('newrelic', {}).get('config'):
import newrelic.agent
newrelic.agent.initialize(
config.newrelic.config, config.newrelic.environment or None, config.newrelic.ignore_errors or None,
config.newrelic.log_file or None, config.newrelic.log_level or None)
# New in 2.0 - override gunicorn-set Server HTTP header
gunicorn.SERVER_SOFTWARE = config.misc.get('http_server_header', 'Zato')
# Store KVDB config in logs, possibly replacing its password if told to
kvdb_config = get_kvdb_config_for_log(config.kvdb)
kvdb_logger.info('Master process config `%s`', kvdb_config)
# New in 2.0 hence optional
user_locale = config.misc.get('locale', None)
if user_locale:
locale.setlocale(locale.LC_ALL, user_locale)
value = 12345
logger.info('Locale is `%s`, amount of %s -> `%s`', user_locale, value,
locale.currency(value, grouping=True).decode('utf-8'))
# Spring Python
app_context = get_app_context(config)
# Makes queries against Postgres asynchronous
if asbool(config.odb.use_async_driver) and config.odb.engine == 'postgresql':
make_psycopg_green()
# New in 2.0 - Put HTTP_PROXY in os.environ.
http_proxy = config.misc.get('http_proxy', False)
if http_proxy:
os.environ['http_proxy'] = http_proxy
crypto_manager = get_crypto_manager(repo_location, app_context, config)
parallel_server = app_context.get_object('parallel_server')
zato_gunicorn_app = ZatoGunicornApplication(parallel_server, repo_location, config.main, config.crypto)
parallel_server.crypto_manager = crypto_manager
parallel_server.odb_data = config.odb
parallel_server.host = zato_gunicorn_app.zato_host
parallel_server.port = zato_gunicorn_app.zato_port
parallel_server.repo_location = repo_location
parallel_server.base_dir = base_dir
parallel_server.tls_dir = os.path.join(parallel_server.base_dir, 'config', 'repo', 'tls')
parallel_server.fs_server_config = config
parallel_server.user_config.update(config.user_config_items)
parallel_server.startup_jobs = app_context.get_object('startup_jobs')
parallel_server.app_context = app_context
# Remove all locks possibly left over by previous server instances
kvdb = app_context.get_object('kvdb')
kvdb.component = 'master-proc'
clear_locks(kvdb, config.main.token, config.kvdb, crypto_manager.decrypt)
#.........这里部分代码省略.........
开发者ID:grenzi,项目名称:ctakes_exploration,代码行数:101,代码来源:main.py
注:本文中的pymysql.install_as_MySQLdb函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论