本文整理汇总了Python中pymysql.install_as_MySQLdb函数的典型用法代码示例。如果您正苦于以下问题:Python install_as_MySQLdb函数的具体用法?Python install_as_MySQLdb怎么用?Python install_as_MySQLdb使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了install_as_MySQLdb函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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();
示例2: use_pymysql
def use_pymysql():
try:
from pymysql import install_as_MySQLdb
except ImportError:
pass
else:
install_as_MySQLdb()
示例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
示例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)
示例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
示例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__()
示例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
示例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()
示例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
示例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)
示例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
示例12: install_project_hook
def install_project_hook():
import pymysql
pymysql.install_as_MySQLdb()
示例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,
#.........这里部分代码省略.........
示例14: install_as_MySQLdb
from pymysql import install_as_MySQLdb
install_as_MySQLdb()
示例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)