本文整理匯總了Python中pymysql.escape_string方法的典型用法代碼示例。如果您正苦於以下問題:Python pymysql.escape_string方法的具體用法?Python pymysql.escape_string怎麽用?Python pymysql.escape_string使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類pymysql
的用法示例。
在下文中一共展示了pymysql.escape_string方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: backtracking_id
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import escape_string [as 別名]
def backtracking_id(site):
cookies = cookies_raw2jar(site['cookies'])
for _tid in range(site['start_torrent'], site['end_torrent'] + 2):
t0 = time.time()
_link = site['torrent_url'].format(_tid)
torrent_page = requests.get(_link, cookies=cookies, headers=headers)
title_search = re.search(site['search_ptn'], torrent_page.text)
if title_search:
_title = pymysql.escape_string(unescape(title_search.group("title")))
pubDate = re.search("發布於(.+?)<", torrent_page.text).group(1)
_timestamp = time.mktime(time.strptime(pubDate, "%Y-%m-%d %H:%M:%S"))
wrap_insert(site=site['name'], sid=_tid, title=_title, link=_link, pubdate=_timestamp, t=t0)
else:
print("ID: {}, Cost: {:.5f} s, No torrent.".format(_tid, time.time() - t0))
time.sleep(2)
示例2: select_sql_params
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import escape_string [as 別名]
def select_sql_params(self, pk=0, fields=[], search_fields=[]):
where, limit, order = '', '', ''
if pk:
where = 'WHERE id="%d"' % pk
elif self.request.arguments:
if not self.get_argument('search', None):
where_fields = [field for field in fields if self.get_argument(field, None) != None]
if where_fields:
where = ' WHERE %s' % ' and '.join(
['%s in (%s)' % (field, ','.join(
['"%s"' % pymysql.escape_string(v) for v in self.get_arguments(field)]))
for field in where_fields])
else:
where = 'WHERE concat(%s) like "%%%s%%"' % (','.join(search_fields),
pymysql.escape_string(self.get_argument('search')))
if self.get_argument('offset', None) and self.get_argument('limit', None):
limit = 'LIMIT %s, %s' % (pymysql.escape_string(self.get_argument('offset')),
pymysql.escape_string(self.get_argument('limit')))
if self.get_argument('order', None) and self.get_argument('sort', None):
order = 'ORDER BY %s %s' % (pymysql.escape_string(self.get_argument('sort')),
pymysql.escape_string(self.get_argument('order')))
return where, order, limit
示例3: auditlog
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import escape_string [as 別名]
def auditlog(self):
if self.reqdata.get('password'):
self.reqdata['password'] = '*' * 6
insert_sql = '''
INSERT INTO
auditlog (
user_id,
uri,
method,
reqdata,
record_time)
VALUES ("%s", "%s", "%s", "%s", "%s")
''' % (self.requser['id'],
self.request.uri,
self.request.method,
pymysql.escape_string(json.dumps(self.reqdata)),
datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
try:
with self.transaction():
self.cursor.execute(insert_sql)
except Exception as e:
logger.error('Add auditlog failed: %s' % str(e))
示例4: select_sql_params
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import escape_string [as 別名]
def select_sql_params(self, pk=0, fields=[], search_fields=[]):
where, limit, order = '', '', ''
if pk:
where = 'WHERE id="%d"' % pk
elif self.request.arguments:
if not self.get_argument('search', None):
where_fields = [field for field in fields if self.get_argument(field, None) != None]
if where_fields:
where = ' WHERE %s' % ' and '.join(
['%s in (%s)' % (field, ','.join(
['"%s"' % pymysql.escape_string(v) for v in self.get_arguments(field)]))
for field in where_fields])
else:
where = 'WHERE concat(%s) like "%%%s%%"' % (','.join(search_fields),
pymysql.escape_string(self.get_argument('search')))
if self.get_argument('offset', None) and self.get_argument('limit', None):
limit = 'LIMIT %s, %s' % (pymysql.escape_string(self.get_argument('offset')),
pymysql.escape_string(self.get_argument('limit')))
if self.get_argument('order', None) and self.get_argument('sort', None):
order = 'ORDER BY %s %s' % (pymysql.escape_string(self.get_argument('sort')),
pymysql.escape_string(self.get_argument('order')))
return where, order, limit
示例5: string_sort
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import escape_string [as 別名]
def string_sort(string):
string = re.sub("[\n\r]", " ", string)
return pymysql.escape_string(string)
示例6: test_escape_fallback_encoder
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import escape_string [as 別名]
def test_escape_fallback_encoder(self):
con = self.connections[0]
cur = con.cursor()
class Custom(str):
pass
mapping = {text_type: pymysql.escape_string}
self.assertEqual(con.escape(Custom('foobar'), mapping), "'foobar'")
示例7: test_escape_fallback_encoder
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import escape_string [as 別名]
def test_escape_fallback_encoder(self):
con = self.connections[0]
cur = con.cursor()
class Custom(str):
pass
mapping = {pymysql.text_type: pymysql.escape_string}
self.assertEqual(con.escape(Custom('foobar'), mapping), "'foobar'")
示例8: write_to_file
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import escape_string [as 別名]
def write_to_file(link,cur):
for keyID,Other in link.items():# KeywordID , Other(Link,Keyword,Word)
for k,pages_v in Other.items(): # Keyword , other(Word , Link)
for w,links in pages_v.items(): # Word , Link
for link in links:
cur.execute('INSERT INTO KeywordsLinks(Link,KeyWordID) VALUES ("%s","%d")' % (pymysql.escape_string(link),keyID))
cur.connection.commit()
示例9: get_keyword_sentence
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import escape_string [as 別名]
def get_keyword_sentence(cur):
cur.execute("select * from KeywordsLinks")
results = cur.fetchall()
for result in results:
try:
print(result)
link=result[1]
LinkID=result[0]
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 '
'(KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
}
cur.execute("select Word from KeyWords,KeywordsLinks where KeywordsLinks.KeyWordID= KeyWords.KeyWordID and KeywordsLinks.LinkID=(%d)" % int(LinkID))
keyword=(cur.fetchone())[0]
pattern=re.compile(r'.{5,20}'+keyword+r'.{5,20}',re.S)
replace=re.compile(r'<.*?>')
page = requests.get(link, headers=headers,timeout=1)
page=replace.sub('',page.text)
items=re.findall(pattern,page)
con=""
for item in items:
con+=item
print(LinkID)
print(len(con))
cur.execute("""UPDATE KeywordsLinks SET Content="%s" WHERE LinkID=%d""" % (pymysql.escape_string(con),LinkID))#escape_string將用戶的輸入進行轉義,防止SQL注入
cur.connection.commit()
time.sleep(random.random())
except Exception:
pass
#刪除表中的空值
示例10: rotate
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import escape_string [as 別名]
def rotate(record, newpassword):
user = record.login
oldpassword = record.password
try:
host = record.get('cmdr:host')
port = record.get('cmdr:port') or '3306'
user_host = record.get('cmdr:user_host') or '%'
with pymysql.connect(host=host, port=int(port), user=user, password=oldpassword) as cursor:
is_old_version = True
affected = cursor.execute('select @@version')
if affected == 1:
rs = cursor.fetchone()
version = rs[0] # type: str
vc = version.split('.')
vn = 0
if len(vc) == 3:
for n in vc:
vn *= 1000
vn += int(n)
is_old_version = vn < 5007006
if is_old_version:
sql = f'set password for \'{user}\'@\'{user_host}\' = password(\'{pymysql.escape_string(newpassword)}\')'
else:
sql = f'alter user \'{user}\'@\'{user_host}\' identified by \'{pymysql.escape_string(newpassword)}\''
cursor.execute(sql)
record.password = newpassword
return True
except pymysql.err.OperationalError as e:
logging.error("MySQL Plugin Error: Unable to establish connection: %s", e)
except pymysql.err.ProgrammingError as e:
logging.error("MySQL Plugin Syntax Error: %s", e)
except Exception as e:
logging.error("MySQL password rotation error: %s", e)
return False
示例11: get_data_clone_id
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import escape_string [as 別名]
def get_data_clone_id(self, key, site) -> None or int:
clone_id = None
key = pymysql.escape_string(re.sub(r"[_\-. ]", "%", key))
sql = "SELECT `{site}` FROM `info_list` WHERE `search_name` LIKE '{key}'".format(site=site, key=key)
try: # Get clone id info from database
clone_id = int(self.exec(sql=sql)[0])
except TypeError: # The database doesn't have the search data, Return dict only with raw key.
logging.warning(
"No record for key: \"{key}\" in \"{site}\". Or may set as `None`".format(key=key, site=site)
)
return clone_id
示例12: test_escape_fallback_encoder
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import escape_string [as 別名]
def test_escape_fallback_encoder(self):
con = self.connect()
cur = con.cursor()
class Custom(str):
pass
mapping = {text_type: pymysql.escape_string}
self.assertEqual(con.escape(Custom('foobar'), mapping), "'foobar'")
示例13: argements_valid
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import escape_string [as 別名]
def argements_valid(handler, pk=None):
error = dict()
name = handler.get_argument('name', '')
path = handler.get_argument('path', '')
comment = handler.get_argument('comment', '')
host = handler.get_argument('host', '')
monitor_choice = handler.get_argument('monitor_choice', '0')
if not path:
error['path'] = 'Required'
else:
select_sql = 'SELECT id FROM logfile WHERE name="%s" %s'
select_arg = (pymysql.escape_string(name), 'and id!="%d"' % pk if pk else '')
count = handler.cursor.execute(select_sql % select_arg)
if count:
error['path'] = 'Already existed'
for i, j in ((name, 'name'), (host, 'host'), (comment, 'comment')):
if not i:
error[j] = 'Required'
if monitor_choice not in ('0', '-1'):
error['monitor_choice'] = 'Invalid'
data = dict(name=name,
path=path,
comment=comment,
host=host,
hosts=host.split(','),
monitor_choice=int(monitor_choice))
return error, data
示例14: init_session
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import escape_string [as 別名]
def init_session(self):
self.session_id = self.get_secure_cookie('session_id')
self.session = None
if self.session_id:
session_id = self.session_id.decode('utf-8')
select_sql = '''
SELECT * FROM session WHERE session_id="%s" and expire_time>="%s"
''' % (pymysql.escape_string(session_id), time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
self.cursor.execute(select_sql)
self.session = self.cursor.dictfetchone()
示例15: get_valid
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import escape_string [as 別名]
def get_valid(func):
def _wrapper(self):
error = {}
logfile = self.get_argument('logfile', '')
match = self.get_argument('match', '')
if not logfile:
error['logfile'] = 'Required'
else:
if logfile.isnumeric():
select_sql = 'SELECT * FROM logfile WHERE id="%s"' % (int(logfile))
else:
select_sql = 'SELECT * FROM logfile WHERE name="%s"' % pymysql.escape_string(logfile)
self.cursor.execute(select_sql)
logfile = self.cursor.dictfetchone()
if not logfile:
error['logfile'] = 'Not exist'
if error:
self._write(dict(code=400, msg='Bad GET param', error=error))
return
self.reqdata = dict(
logfile=logfile,
match=match,
)
return func(self)
return _wrapper