Python MySQLdb.escape_string() Examples

The following are code examples for showing how to use MySQLdb.escape_string(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: AI2-Reasoning-Challenge-ARC   Author: SebiSebi   File: pmi_utils.py    GNU General Public License v3.0 6 votes vote down vote up
def fetch_coo_or_none(self, pair):
        assert(isinstance(pair, tuple))
        assert(len(pair) == 2)

        w1 = [x.lower() for x in pair[0]]
        w2 = [x.lower() for x in pair[1]]
        word = "%[({})]% AND %[({})]%".format("|".join(w1),
                                              "|".join(w2))
        word = MySQLdb.escape_string(word).decode()
        table = "cooccurrences"
        session = self.db.cursor()
        session.execute("""SELECT logp FROM {}
                           WHERE word = '{}'""".format(table, word))
        logp = session.fetchone()
        if logp is None:
            return None
        logp = float(logp[0])
        return logp 
Example 2
Project: AI2-Reasoning-Challenge-ARC   Author: SebiSebi   File: pmi_utils.py    GNU General Public License v3.0 6 votes vote down vote up
def save_cooccurrence(self, pair, logp):
        assert(isinstance(pair, tuple))
        assert(len(pair) == 2)

        w1 = [x.lower() for x in pair[0]]
        w2 = [x.lower() for x in pair[1]]
        word = "%[({})]% AND %[({})]%".format("|".join(w1),
                                              "|".join(w2))
        try:
            word = MySQLdb.escape_string(word).decode()
            table = "cooccurrences"
            session = self.db.cursor()
            session.execute("""INSERT INTO {}(word, logp)
                               VALUES('{}', {})""".format(table, word, logp))
        except Exception as e:
            print("[PMI] WARNING! " + str(e)) 
Example 3
Project: TripMeal   Author: DanielAndreasen   File: app.py    MIT License 6 votes vote down vote up
def login_page():
    try:
        error = None
        c, conn = connection()
        if request.method == 'POST':
            username = escape_string(request.form['username']).decode()
            data = c.execute('SELECT * FROM users WHERE username = ("%s");' % username)
            data = c.fetchone()
            if sha256_crypt.verify(request.form['password'], data[2]) and (data[1] == username):
                session['logged_in'] = True
                session['username'] = username
                session['favourites'] = data[4]
                flash('You are now logged in')
                return redirect(url_for('user_page'))
            else:
                error = 'Invalid credentials, try again'
        gc.collect()
        return render_template('login.html', error=error)
    except:
        error = 'Invalid credentials, try again'
        return render_template('login.html', error=error) 
Example 4
Project: TripMeal   Author: DanielAndreasen   File: app.py    MIT License 6 votes vote down vote up
def addrecipe():
    if request.method == 'POST':
        title = escape_string(request.form['title'])
        location = escape_string(request.form['country'])
        ingredients = escape_string(','.join(request.form['ingredients'].split('\r\n')).strip(','))
        recipe = escape_string(request.form['recipe'])
        username = session['username']
        c, conn = connection()

        c.execute('INSERT INTO recipes (title, location, ingredients, recipe, user) VALUES ("%s", "%s", "%s", "%s", "%s");' %
                                       (title, location, ingredients, recipe, username))
        conn.commit()  # Save to the database
        flash("Thanks for your recipe :)")
        c.close()
        conn.close()
        gc.collect()  # Garbage collection

        return redirect(url_for('newrecipe'))
    else:
        return render_template('main.html') 
Example 5
Project: IHP   Author: lasigeBioTM   File: chebi_resolution.py    MIT License 6 votes vote down vote up
def find_chebi_term2(term):
    if _platform == "linux" or _platform == "linux2":
        # linux
        cp = "{0}/florchebi.jar:{0}/mysql-connector-java-5.1.24-bin.jar:{0}/Tokenizer.jar".format(florchebi_path)
    elif _platform == "win32":
        # "Windows..."
        cp = "{0}/florchebi.jar;{0}/mysql-connector-java-5.1.24-bin.jar;{0}/Tokenizer.jar".format(florchebi_path)
    florcall = ["java", "-cp", cp, "xldb.flor.match.FlorTextChebi3star", db.escape_string(term),
                "children", "true", "mychebi201301", "false", "false", "chebi", stoplist, "1"]
    # print ' '.join(florcall)
    flor = Popen(florcall, stdout=PIPE)
    florresult, error = flor.communicate()
    chebires = florresult.strip().split('\t')
    # print "chebires: ", chebires
    if len(chebires) == 3:
        return (chebires[0], chebires[1], float(chebires[2]))
    else:
        return ('0', 'null', 0.0) 
Example 6
Project: TvCalendarShellNew   Author: zhuyf8899   File: database.py    GNU General Public License v2.0 6 votes vote down vote up
def insertShowFirstTime(self,obj):#obj中必须有s_name,link,status和s_sibox_image
        try:
            #首先从资源库中找id
            obj['s_name'] = MySQLdb.escape_string(obj['s_name'])
            dbrc = self.connect('resource')
            dbrcHandler = dbrc.cursor()
            sqlGetResource = 'select zmz_resourceid from zmz_resource where resource_en_name = \'%s\' limit 1'%(obj['s_name'])
            dbrcHandler.execute(sqlGetResource)
            resourceResult = dbrcHandler.fetchone()
            #print(resourceResult)
            dbrc.close()
            if resourceResult != None:
                resourceId = resourceResult[0]
            else:
                resourceId = ''
        except Exception,e:
            print(e)
            self.log.takeLog('ERROR','connecting to resource database error:'+str(e)+'\n the sql='+sqlGetResource)
            dbrc.close()
            return "Error" 
Example 7
Project: TvCalendarShellNew   Author: zhuyf8899   File: database.py    GNU General Public License v2.0 6 votes vote down vote up
def updateShowDetail(self,obj):#obj中必须有s_id,s_description,update_time,area,channel,status 和length
        try:
            obj['s_description'] = MySQLdb.escape_string(obj['s_description'])
            obj['channel'] = MySQLdb.escape_string(obj['channel'])
            obj['status'] = MySQLdb.escape_string(obj['status'])
            dbc = self.connect()
            cursor = dbc.cursor()
            sqlUpdate = '''UPDATE `shows` SET `s_description` = \'%s\',`update_time` = \'%s\',`area` = \'%s\',`length` = \'%s\',`channel` = \'%s\',`status` = \'%s\' WHERE `s_id` = \'%s\''''%(obj['s_description'],obj['update_time'],obj['area'],obj['length'],obj['channel'],obj['status'],obj['s_id'])
            cursor.execute(sqlUpdate)
            dbc.commit()
            dbc.close()
            print('update details: '+ str(obj['s_id']))
            return "OK"
        except Exception,e:
            print(e)
            #print(sqlUpdate)
            self.log.takeLog('ERROR','Table show updating error:'+str(e)+'\n the sql='+sqlUpdate)
            dbc.close()
            return "Error" 
Example 8
Project: dd-streamworks   Author: ddinsight   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def __new__(cls, state, bssid, ssid='', regdtm='19000101000000', rssi=-200, bregap=False, bmap=False, optrcom='none', geoloc=None, priority=Priority.NORMAL):
        # Classify WiFi
        try:
            if ssid not in ('', None):
                ssid = re.sub(r'^\s*"(.*)"\s*$', r'\1', unicode(ssid))
                if ssid.find('"') >= 0:
                    log.error("!!! SSID - %s" % ssid)
                if cls.isHotspot(ssid):
                    priority = Priority.LOW
                else:
                    optrcom = cls.getWiFiOperator(ssid)
                    bregap = True if optrcom != 'none' else False
                    if not bregap:
                        bmap = cls.isMobile(ssid)

                try:
                    ssid = MySQLdb.escape_string(unicode(ssid).encode('utf-8'))
                except Exception, e:
                    # Non-ascii data.
                    log.warn("SSID MySQLdb.escape_string Error - %s, %s" % (ssid, e))

            if not geoloc:
                geoloc = GeoInfo() 
Example 9
Project: IBRel   Author: lasigeBioTM   File: chebi_resolution.py    MIT License 6 votes vote down vote up
def find_chebi_term2(term):
    if _platform == "linux" or _platform == "linux2":
        # linux
        cp = "{0}/florchebi.jar:{0}/mysql-connector-java-5.1.24-bin.jar:{0}/Tokenizer.jar".format(florchebi_path)
    elif _platform == "win32":
        # "Windows..."
        cp = "{0}/florchebi.jar;{0}/mysql-connector-java-5.1.24-bin.jar;{0}/Tokenizer.jar".format(florchebi_path)
    florcall = ["java", "-cp", cp, "xldb.flor.match.FlorTextChebi3star", db.escape_string(term),
                "children", "true", "mychebi201301", "false", "false", "chebi", stoplist, "1"]
    # print ' '.join(florcall)
    flor = Popen(florcall, stdout=PIPE)
    florresult, error = flor.communicate()
    chebires = florresult.strip().split('\t')
    # print "chebires: ", chebires
    if len(chebires) == 3:
        return (chebires[0], chebires[1], float(chebires[2]))
    else:
        return ('0', 'null', 0.0) 
Example 10
Project: gthx   Author: gunnbr   File: DbAccess.py    GNU General Public License v2.0 5 votes vote down vote up
def seen(self, nick):
        nick = string.replace(nick,"*","%")
        return self.executeAndFetchAll("SELECT * FROM seen WHERE name LIKE %s ORDER BY timestamp DESC LIMIT 3", MySQLdb.escape_string(nick)) 
Example 11
Project: AI2-Reasoning-Challenge-ARC   Author: SebiSebi   File: pmi_utils.py    GNU General Public License v3.0 5 votes vote down vote up
def fetch_logp_or_none(self, ngram):
        assert(self.db is not None)
        assert(isinstance(ngram, tuple) or isinstance(ngram, str))
        words = None
        if isinstance(ngram, tuple):
            words = [x.lower() for x in ngram]
            assert(len(words) in [2, 3])
        else:
            words = [ngram.lower()]
        assert(len(words) >= 1 and len(words) <= 3)
        table = None
        word = None
        if len(words) == 1:
            word = words[0].lower()
            table = "unigrams"
        elif len(words) == 2:
            word = "|".join(words)
            table = "bigrams"
        elif len(words) == 3:
            word = "|".join(words)
            table = "trigrams"

        # Query MySQL db with the right word and table.
        word = MySQLdb.escape_string(word).decode()
        session = self.db.cursor()
        session.execute("""SELECT logp FROM {}
                           WHERE word = '{}'""".format(table, word))
        logp = session.fetchone()
        if logp is None:
            return None
        logp = float(logp[0])
        return logp 
Example 12
Project: AI2-Reasoning-Challenge-ARC   Author: SebiSebi   File: pmi_utils.py    GNU General Public License v3.0 5 votes vote down vote up
def save_ngram(self, ngram, logp):
        assert(self.db is not None)
        assert(isinstance(ngram, tuple) or isinstance(ngram, str))

        words = None
        if isinstance(ngram, tuple):
            words = [x.lower() for x in ngram]
        else:
            words = [ngram]
        assert(len(words) >= 1 and len(words) <= 3)
        table = None
        word = None
        if len(words) == 1:
            word = words[0].lower()
            table = "unigrams"
        elif len(words) == 2:
            word = "|".join(words)
            table = "bigrams"
        elif len(words) == 3:
            word = "|".join(words)
            table = "trigrams"
        else:
            assert(False)
        try:
            word = MySQLdb.escape_string(word).decode()
            session = self.db.cursor()
            session.execute("""INSERT INTO {}(word, logp)
                               VALUES('{}', {})""".format(table, word, logp))
        except Exception as e:
            print("[PMI] WARNING! " + str(e)) 
Example 13
Project: taobao   Author: nosun   File: mysqlstore.py    Apache License 2.0 5 votes vote down vote up
def _format(self, item):
        item['images'] = MySQLdb.escape_string(repr(item['images']))
        item['choices'] = MySQLdb.escape_string(repr(item['choices']))
        item['properties'] = MySQLdb.escape_string(repr(item['properties']))
        return item 
Example 14
Project: iOS-private-api-checker   Author: NetEaseGame   File: mysql_escape_warp.py    GNU General Public License v2.0 5 votes vote down vote up
def _str_escape(s, d):
    if s == None:
        return ''
    return MySQLdb.escape_string(s) 
Example 15
Project: iOS-private-api-checker   Author: NetEaseGame   File: mysql_escape_warp.py    GNU General Public License v2.0 5 votes vote down vote up
def mysql_escape(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        newargs = []
        #先转义参数,再执行方法
        for arg in args:
            #字符串,包括中文
            if type(arg) is types.StringType or type(arg) is types.UnicodeType:
                newargs.append(MySQLdb.escape_string(arg))
            
            #字典    
            elif isinstance(arg, dict):
                newargs.append(MySQLdb.escape_dict(arg, {
                                                         types.StringType: _str_escape,
                                                         types.UnicodeType: _str_escape,
                                                         types.IntType: _no_escape,
                                                         types.FloatType: _no_escape
                                                         }))
            #其他类型不转义
            else:
                newargs.append(arg)
                
        newargs = tuple(newargs)
        
        func = f(*newargs, **kwargs)
        
        return func
    return decorated_function 
Example 16
Project: TripMeal   Author: DanielAndreasen   File: app.py    MIT License 5 votes vote down vote up
def register_page():
    form = RegistrationForm(request.form)
    try:
        if request.method == 'POST' and form.validate():
            username = form.username.data
            email = form.email.data
            password = sha256_crypt.encrypt(str(form.password.data))

            c, conn = connection()
            x = c.execute('SELECT * FROM users WHERE username = ("%s");' %
                             escape_string(username))
            if int(x) > 0:
                flash('That username is already taken, please choose another')
                return render_template('register.html', form=form)
            else:
                c.execute('INSERT INTO users (username, password, email) VALUES ("%s", "%s", "%s");' %
                          (escape_string(username), escape_string(password), escape_string(email)))
                conn.commit()
                flash('Thanks for registering!')
                c.close()
                conn.close()
                gc.collect()

                session['logged_in'] = True
                session['username'] = username
                return redirect(url_for('favourites_page'))
        return render_template('register.html', form=form)
    except Exception as e:
        return render_template('register.html', form=form) 
Example 17
Project: TripMeal   Author: DanielAndreasen   File: app.py    MIT License 5 votes vote down vote up
def edit_recipe(rid):
    # Get the recipe
    # c.execute('INSERT INTO recipes (title, location, ingredients, recipe, user) VALUES ("%s", "%s", "%s", "%s", "%s");' %
    c, conn = connection()
    _ = c.execute('SELECT * FROM recipes WHERE rid="%s"' % rid)
    recipe = c.fetchone()
    c.close()
    conn.close()
    gc.collect()

    # Fill the form
    form = RecipeForm(request.form)
    form.title.data = recipe[1]
    form.country.data = recipe[2]
    form.ingredients.data = '\n'.join(recipe[3].split(','))
    form.recipe.data = recipe[4]

    if request.method == 'POST':
        title = escape_string(request.form['title'])
        country = escape_string(request.form['country'])
        ingredients = escape_string(','.join(request.form['ingredients'].split('\r\n')).strip(','))
        recipe = escape_string(request.form['recipe'])

        # Update the DB
        c, conn = connection()
        c.execute('UPDATE recipes SET title="%s", location="%s", ingredients="%s", recipe="%s" WHERE rid=%s' % (title, country, ingredients, recipe, rid))
        conn.commit()

        # Close connection
        c.close()
        conn.close()
        gc.collect()

        flash('Recipe updated')

        return redirect(url_for('user_page'))

    return render_template('edit_recipe.html', form=form) 
Example 18
Project: pykit   Author: bsc-s2   File: mysqlutil.py    MIT License 5 votes vote down vote up
def _safe(s):
    return '"' + MySQLdb.escape_string(str(s)) + '"' 
Example 19
Project: ops   Author: xiaomatech   File: jumserver.py    MIT License 5 votes vote down vote up
def __init__(self, datetime, cmd):
        self.msg = str(datetime) + '\r\r' + cmd + '\r\n\r\n\r\n'
        if is_log2db:
            try:
                global log_id
                db._ensure_connected()
                db.insert(
                    "INSERT INTO ttylog (`datetime`,`cmd`,`log_id`) VALUES ('%s','%s','%d')"
                    % (str(datetime), MySQLdb.escape_string(cmd), log_id))
            except Exception as err:
                pass 
Example 20
Project: ops   Author: xiaomatech   File: jumserver.py    MIT License 5 votes vote down vote up
def __init__(self, host, cmd, remote_ip, result):
        self.msg = str(
            host) + '\r\r' + cmd + '\r\r' + remote_ip + '\r\r' + str(result)
        sql = "INSERT INTO execlog (`user`,`host`,`cmd`,`remote_ip`,`result`) VALUES (%s,%s,%s,%s,%s)"
        if is_log2db:
            try:
                db._ensure_connected()
                db.insert(sql, user, host,
                          MySQLdb.escape_string(cmd), remote_ip,
                          MySQLdb.escape_string(str(result)))
            except Exception as err:
                pass 
Example 21
Project: ops   Author: xiaomatech   File: jumserver.py    MIT License 5 votes vote down vote up
def __init__(self, host, filename, type, remote_ip, result):
        self.msg = str(
            host
        ) + '\r\r' + filename + '\r\r' + type + '\r\r' + remote_ip + '\r\r' + str(
            result) + '\r\n\r\n\r\n'
        if is_log2db:
            try:
                db._ensure_connected()
                db.insert(
                    "INSERT INTO filelog (`user`,`host`,`filename`,`type`,`remote_ip`,`result`) VALUES ('%s','%s','%s','%s','%s','%s')"
                    % (user, host, filename, type, remote_ip,
                       MySQLdb.escape_string(str(result))))
            except Exception as err:
                pass 
Example 22
Project: coyote_framework   Author: Shapeways   File: coyote_db.py    MIT License 5 votes vote down vote up
def db_escape(string):
        """Escapes special characters in a string

        @param string: The string to escape
        @return: String with escaped special characters
        """
        string = MySQLdb.escape_string(string)
        return string 
Example 23
Project: IHP   Author: lasigeBioTM   File: protein_entity.py    MIT License 5 votes vote down vote up
def normalize(self):
        term = MySQLdb.escape_string(self.text)
        # adjust - adjust the final score
        match = ()
        cur = db.cursor()
        # synonym
        query = """SELECT DISTINCT t.acc, t.name, s.term_synonym
                       FROM term t, term_synonym s
                       WHERE s.term_synonym LIKE %s and s.term_id = t.id
                       ORDER BY t.ic ASC
                       LIMIT 1;""" # or DESC
            # print "QUERY", query

        cur.execute(query, ("%" + term + "%",))

        res = cur.fetchone()
        if res is not None:
            print res
        else:
            query = """SELECT DISTINCT t.acc, t.name, p.name
                       FROM term t, prot p, prot_GOA_BP a
                       WHERE p.name LIKE %s and p.id = a.prot_id and a.term_id = t.id
                       ORDER BY t.ic ASC
                       LIMIT 1;""" # or DESC
            cur.execute(query, (term,))
            res = cur.fetchone()
            print res 
Example 24
Project: heron   Author: Eastwu5788   File: filter_plugin.py    MIT License 5 votes vote down vote up
def __call__(self, *args, **kwargs):
        super(TypeFilter, self).__call__()

        direct_type = self.rule.direct_type

        # 初始类型就是字符串,并且默认是安全的,则不需要处理
        if isinstance(self.value, direct_type) and self.rule.safe:
            return self.value

        if direct_type == str:
            if self.rule.safe:
                return self.value
            else:
                # 允许为空并且值为空
                if self.rule.allow_empty and not self.value:
                    return self.value

                import MySQLdb
                self.value = MySQLdb.escape_string(self.value)
                if isinstance(self.value, bytes):
                    self.value = self.value.decode('utf-8')
                return self.value
        # 特殊的字符串转bool类型
        elif direct_type == bool and self.value in _false_str_list:
            return False
        else:
            try:
                if self.value is None:
                    if self.rule.direct_type == int:
                        self.value = 0
                    elif self.rule.direct_type == str:
                        self.value = ""
                return self.rule.direct_type(self.value)
            except ValueError:
                raise ParamsValueError(self.error_code, filter=self) 
Example 25
Project: TvCalendarShellNew   Author: zhuyf8899   File: database.py    GNU General Public License v2.0 5 votes vote down vote up
def insertEpisode(self,aRecord):
        try:
            aRecord['e_name'] = MySQLdb.escape_string(aRecord['e_name'])
            dbc = self.connect()
            cursor = dbc.cursor()
            sqlCheck = '''select e_id,e_name,e_status,DATE_FORMAT(e_time,'%%Y-%%m-%%d %%T') from episode where s_id = %s AND se_id = %s AND e_num = %s'''%(aRecord['s_id'],aRecord['se_id'],aRecord['e_num'])
            cursor.execute(sqlCheck)
            checker = cursor.fetchone()
            if checker:
                checkerOne =  MySQLdb.escape_string(checker[1])#此处不允许直接修改checker
                #print(checker)
                if checkerOne == aRecord['e_name'] and checker[2] == aRecord['e_status'] and checker[3] == aRecord['e_time']:
                    print('An episode record has been existed:'+str(aRecord['s_id'])+':S'+str(aRecord['se_id'])+'E'+str(aRecord['e_num']))
                    dbc.close()
                    return "Repeat"
                else:
                    #self.log.takeLog('DEBUG','Before update a episode,record in db is :'+checker[1]+'|||'+checker[2]+'|||'+checker[3])
                    #self.log.takeLog('DEBUG','Before update a episode,record in py is :'+aRecord['e_name']+'|||'+aRecord['e_status']+'|||'+aRecord['e_time'])
                    sql = '''UPDATE `episode` SET `e_name` = \'%s\',`e_status` = \'%s\',`e_description` = \'%s\',`e_time` = \'%s\' WHERE `e_id` = \'%s\''''%(aRecord['e_name'],aRecord['e_status'],aRecord['e_description'],aRecord['e_time'],checker[0])
                    cursor.execute(sql)
                    dbc.commit()
                    print('An episode record has been updated:'+str(checker[0]))
                    #self.log.takeLog('DEBUG','An episode record has been updated:'+str(checker[0]))
                    dbc.close()
                    return "Update"
            else:
                sql = '''insert into episode(s_id,se_id,e_name,e_num,e_status,e_description,e_time) values(\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\')'''%(aRecord['s_id'],aRecord['se_id'],aRecord['e_name'],aRecord['e_num'],aRecord['e_status'],aRecord['e_description'],aRecord['e_time'])
                cursor.execute(sql)
                dbc.commit()
                dbc.close()
                print('A record has been inserted:'+str(aRecord['s_id'])+':S'+str(aRecord['se_id'])+'E'+str(aRecord['e_num']))
                return "OK"
        except Exception, e:
            self.log.takeLog('ERROR','Table episode inserting error:'+ str(e)+' \nthe sql = '+sql+'\nthe e_name is %s'%(aRecord['e_name']))
            dbc.close()
            return "Error" 
Example 26
Project: TvCalendarShellNew   Author: zhuyf8899   File: database.py    GNU General Public License v2.0 5 votes vote down vote up
def insertTag(self,showId,tagName):
        try:
            tagName = MySQLdb.escape_string(tagName)
            dbc = self.connect()
            cursor = dbc.cursor()
            sqlCheck = '''select t_id from tag where t_name = \'%s\' limit 1'''%(tagName)
            sqlCheckStT = ''
            sqlInsToStT = ''
            sqlInsToTag = ''
            cursor.execute(sqlCheck)
            checker = cursor.fetchone()
            if checker:
                sqlCheckStT = '''select * from show_to_tag where s_id = %s and t_id = %s limit 1'''%(str(showId),str(checker[0]))
                cursor.execute(sqlCheckStT)
                checkerStT = cursor.fetchone()
                if checkerStT:
                    print('A tag relationship has been exist:tag_id-'+str(checker[0])+' to show_id-'+str(showId))
                    return "Repeat"
                else:
                    sqlInsToStT = '''insert into show_to_tag(s_id,t_id) values(%s,%s)'''%(showId,str(checker[0]))
                    cursor.execute(sqlInsToStT)
                    dbc.commit()
                    dbc.close()
                    print('A tag relationship has been set:tag_id-'+str(checker[0])+' to show_id-'+str(showId))
                    return "OK"
            else:
                sqlInsToTag = '''insert into tag(t_name) values(\'%s\')'''%(tagName)
                cursor.execute(sqlInsToTag)
                dbc.commit()
                self.insertTag(showId,tagName)
        except Exception, e:
            self.log.takeLog('ERROR','Table tag inserting error:'+ str(e))
            self.log.takeLog('DEBUG','the sqlCheck = '+sqlCheck)
            self.log.takeLog('DEBUG','the sqlCheckStT = '+sqlCheckStT)
            self.log.takeLog('DEBUG','the sqlInsToStT = '+sqlInsToStT)
            self.log.takeLog('DEBUG','the sqlInsToTag = '+sqlInsToTag)
            print(e)
            dbc.close()
            return "Error" 
Example 27
Project: ops   Author: bsc-s2   File: mysqlutil.py    MIT License 5 votes vote down vote up
def _safe(s):
    return '"' + MySQLdb.escape_string(str(s)) + '"' 
Example 28
Project: sc_map_scraper   Author: berossm   File: starmap_json_to_sql.py    MIT License 5 votes vote down vote up
def str_or_none(json_object, key_str):
    if key_str in json_object.keys():
        json_data = json_object[key_str]
        if json_data == None:
            temp_str = "NULL"
        else:
            temp_str = unicode(json_data)
            ascii_str = unidecode(temp_str)
            temp_str = "'" + MySQLdb.escape_string(ascii_str) + "'"
    else:
        temp_str = "NULL"
    return temp_str 
Example 29
Project: fancyMySQL   Author: cppla   File: fancyMysql.py    MIT License 5 votes vote down vote up
def escape_parameter(self, parameter):
        if isinstance(parameter, str):
            return MySQLdb.escape_string(parameter)
        else:
            return MySQLdb.escape(parameter) 
Example 30
Project: KodiDB   Author: theguardian   File: formatter.py    GNU General Public License v2.0 5 votes vote down vote up
def MySQL(string):
    value = MySQLdb.escape_string(string.encode('UTF-8'))
    return value 
Example 31
Project: monitor_mysql_overflows   Author: dalenys   File: SchemaInformation.py    ISC License 5 votes vote down vote up
def in_stmt(self, l):
        return (', '.join(map(lambda x: "'" + escape_string(x) + "'", l))) 
Example 32
Project: monitor_mysql_overflows   Author: dalenys   File: SchemaInformation.py    ISC License 5 votes vote down vote up
def _in_stmt(self, l):
        return (', '.join(map(lambda x: "'" + escape_string(x) + "'", l))) 
Example 33
Project: asm3   Author: bobintetley   File: mysql.py    GNU General Public License v3.0 5 votes vote down vote up
def escape(self, s):
        """ Makes a string value safe for database queries
        """
        if s is None: return ""
        if asm3.utils.is_str(s):
            s = MySQLdb.escape_string(s)
        elif asm3.utils.is_unicode(s):
            # Encode the string as UTF-8 for MySQL escape_string 
            # then decode it back into unicode before continuing
            s = s.encode("utf-8")
            s = MySQLdb.escape_string(s)
            s = s.decode("utf-8")
        # This is historic - ASM2 switched backticks for apostrophes so we do for compatibility
        s = s.replace("'", "`")
        return s 
Example 34
Project: Strava-AeroLabs   Author: BillSkiCO   File: main.py    GNU General Public License v3.0 4 votes vote down vote up
def register_page():
    try:
        form = RegistrationForm(request.form)

        if request.method == "POST" and form.validate():
            # Pull data from html form
            username = form.username.data
            email = form.email.data

            # Immediately encrypt via sha256
            password = sha256_crypt.encrypt((str(form.password.data)))

            # Connect to database
            cursor, conn = connection()

            # Using cursor, select a username in database. inject_attk_check() protects against sql injection.
            un_attempt = cursor.execute("SELECT * FROM users WHERE username = (%s)",
                                        (inject_attk_check(username)))

            # Check to see if username is taken by searching for username in db first.
            # If returned value is longer than 0 then the username is already taken.
            if len(int(un_attempt)) > 0:
                # Call to flask.flash()
                flash("That username is already taken, please try another")
                render_template('register.html', form=form)
            else:
                cursor.execute("INSERT INTO users(username, password, email) VALUES (%s, %s, %s)",
                               inject_attk_check(username), inject_attk_check(password), inject_attk_check(email))

                # Commit changes to database
                conn.commit()
                flash("Thanks for registering")

                # Close cursor and connection
                cursor.close()
                conn.close()

                # Garbage collect after closing database connections. This is to ensure we don't have any leaks.
                gc.collect()

                session["logged_in"] = True
                session['username'] = username

                return redirect(url_for('dashboard'))
        return render_template("register.html", form=form)

    # fix this after debugging
    except Exception as e:
        return str(e)

# Check to make sure we only run the web server when this file is run directly 
Example 35
Project: IBRel   Author: lasigeBioTM   File: protein_entity.py    MIT License 4 votes vote down vote up
def get_best_go(self):
        cur = db.cursor()
        # synonym

        query = """SELECT DISTINCT t.acc, t.name, t.ic
                       FROM term t
                       WHERE t.acc IN (%s)
                       ORDER BY t.ic ASC
                       LIMIT 1;""" # or DESC
            # print "QUERY", query


        format_strings = ','.join(['%s'] * len(self.go_ids))
        cur.execute(query % format_strings, (self.go_ids))
        res = cur.fetchone()
        if res is not None:
            # print self.text, res[1:]
            logging.info("best GO for {}: {}".format(self.text, " ".join([str(r) for r in res])))
            self.best_go = res[0]
        else:
            logging.info("NO GO for {}".format(self.text))
            self.best_go = ""

    # def normalize(self):
    #     term = MySQLdb.escape_string(self.text)
    #     # adjust - adjust the final score
    #     match = ()
    #     cur = db.cursor()
    #     # synonym
    #     query = """SELECT DISTINCT t.acc, t.name, s.term_synonym
    #                    FROM term t, term_synonym s
    #                    WHERE s.term_synonym LIKE %s and s.term_id = t.id
    #                    ORDER BY t.ic ASC
    #                    LIMIT 1;""" # or DESC
    #         # print "QUERY", query
    #
    #     cur.execute(query, ("%" + term + "%",))
    #
    #     res = cur.fetchone()
    #     if res is not None:
    #         print res
    #     else:
    #         query = """SELECT DISTINCT t.acc, t.name, p.name
    #                    FROM term t, prot p, prot_GOA_BP a
    #                    WHERE p.name LIKE %s and p.id = a.prot_id and a.term_id = t.id
    #                    ORDER BY t.ic ASC
    #                    LIMIT 1;""" # or DESC
    #         cur.execute(query, (term,))
    #         res = cur.fetchone()
    #         print res

# token = Token2("IL-2")
# token.start, token.dstart, token.end, token.dend = 0,0,0,0
# p = ProteinEntity([token], "", text=sys.argv[1])
# p.normalize()