Exemple #1
0
def add_task(db, uid, url, ttl = 10, inc = 10, pos = "", neg = "", frr = ""):
    cursor = db.cursor()
    sql = r'''
        select * from task where uid="%s";
    ''' % uid
    #sql = MySQLdb.escape_string(sql)
    pos = MySQLdb.escape_string(pos)
    neg = MySQLdb.escape_string(neg)
    frr = MySQLdb.escape_string(frr)

    ret = cursor.execute(sql)
    cursor.fetchall()

    if ret > 0:
        sql = r'''
                update task set ttl="%d", url="%s", inc="%d", pos="%s", neg="%s", frr="%s" where uid="%s";
            ''' % (ttl, url, inc, pos, neg, frr, uid)
    else:
        sql = r'''
                insert task (uid, ttl, url, inc, pos, neg, frr) values ("%s", %d, "%s", %d, "%s", "%s", "%s");
            ''' % (uid, ttl, url, inc, pos, neg, frr)

    cursor.execute(sql)

    db.commit()
    db.close()
Exemple #2
0
    def get_saler_target_list_by_condition(self,page_num,per_page,create_user,beg_date,end_date):
        where=''

        """SQL防注入"""
        create_user=MySQLdb.escape_string(create_user)
        beg_date=MySQLdb.escape_string(beg_date)
        end_date=MySQLdb.escape_string(end_date)

        if create_user!=0:
            where+='create_user=%s and '%create_user
        if beg_date!='0' and end_date!='0':
            where+='create_date between %s and %s and '%(beg_date,end_date)
        elif end_date=='0':
            where+='create_date>=%s and '%beg_date
        elif beg_date=='0':
            where+='create_date<=%s and '%end_date

        where+='1=1'

        result=pager.result_paged('product',where=where,
                                order="product_create_date DESC",page_num=page_num,per_page=per_page)

        """替换结果集中的人员id"""
        for item in result:
            id=item.create_user
            item.create_user=users.get_users_by_id(id)[0]['real_name']

        return result
Exemple #3
0
def insertSimToDB(pulseseq, params, dec):
    """ create an entry for a Simulation """

    if not mysql:
        return

    entry_ps = repr(pulseseq.seq)
    entry_params = MySQLdb.escape_string(repr(params.__dict__))
    entry_hspace = MySQLdb.escape_string(repr(params.hspace.__dict__))
    entry_dec = MySQLdb.escape_string(repr(dec.__dict__))

    dbx = MySQLdb.connect(user="******", passwd="tiqc_cluster1", db="tiqcspice", host="marvin")
    db = dbx.cursor()

    sql = "insert into Simulation (name, pulseseq, params, hspace, decoherence) values ('%s', '%s','%s','%s','%s')" % (
        dec.doSQLname,
        entry_ps,
        entry_params,
        entry_hspace,
        entry_dec,
    )
    try:
        db.execute(sql)
    except Exception, e:
        print "ERROR in sql insertSimToDB:", e
Exemple #4
0
def save_character(json_data):
    json_dict = simplejson.loads(json_data)
    username = MySQLdb.escape_string(json_dict['username'])
    world_id = MySQLdb.escape_string(json_dict['world_id'])

    # TODO save the character
    return simplejson.dumps({"success": "true"})
Exemple #5
0
def another_page():
  
    print('anotherpage')
    scoop = {'postername': MySQLdb.escape_string(request.form['postername']),
               'activity': MySQLdb.escape_string(request.form['activity']),
               'rank': request.form['rank']
             
               }
    
    if request.method == 'POST':
        db = utils.db_connect()
        cur = db.cursor(cursorclass=MySQLdb.cursors.DictCursor)
        
        query = "INSERT INTO club_name (postername) VALUES ('" + MySQLdb.escape_string(request.form['postername']) + "')"
        # Print query to console (useful for debugging)
        print query
        cur.execute(query)
        id=cur.lastrowid
        #db.commit()
        
        query2 = "INSERT INTO activity (club_id, activity, rank) VALUES (" + str(id) + ", '" + MySQLdb.escape_string(request.form['activity']) + "', '" + request.form['rank'] + "')"
        # Print query to console (useful for debugging)
        print query2
        cur.execute(query2)
        db.commit()
        
        
    cur.execute('SELECT DISTINCT cn.postername, a.activity, a.rank FROM club_name cn NATURAL JOIN activity a')
    rows = cur.fetchall()

    return render_template('another_page.html', club_name=rows, activity = rows, scoop = scoop)
Exemple #6
0
def store_comment(user_name, message, md5):

    # To initial connection
    conn = init_connection()

    # To get current cursor
    cur = conn.cursor()

    user_name = MySQLdb.escape_string(user_name)

    # This set of codes is to get the current user indexID

    # To execute the generated sql text

    cur.execute("""select indexID from users where uName = %s""", user_name)

    # To get one set of data from the return results
    uID = cur.fetchone()

    # To convert format from tuple to string

    uID = str(uID)

    # To split out the user ID from the return results
    uID = uID[1 : +uID.find("L", 1, -1)]

    # This set of codes is to get the supported website indexID

    # To execute the generated sql text
    cur.execute("""select indexID from url where md5 = %s""", md5)

    # To get one set of data from the return results
    urlID = cur.fetchone()

    # To convert format from tuple to string
    urlID = str(urlID)

    # To split out the supported website indexID from the return results
    urlID = urlID[1 : +urlID.find("L", 1, -1)]

    # To execute the generated sql text
    sql = """insert into comments values(null,%s,%s,now(),%s)"""

    message = MySQLdb.escape_string(message)
    args = int(urlID), message, int(uID)

    # To execute the sql
    cur.execute(sql, args)

    # To commit the actions, if not, it will not execbte anything
    conn.commit()

    # To close the current cursor
    cur.close()

    # To kill the connection
    conn.close()

    # To return something
    return "store sucessfully!"
    def from_operational(self, identifier):
        """ Read a project from operational database
        """
        query = """
        SELECT  p.environment_name AS identifier,
                p.project_name,
                u.username AS author,
                p.created,
                p.updated,
                p.published,
                p.project_id
        FROM projects AS p
        INNER JOIN user AS u ON u.user_id = p.author
        WHERE p.environment_name = '%s'""" % identifier

        row = []
        with admin_query() as cursor:
            try:
                cursor.execute(query)
                row = cursor.fetchone()
            except:
                conf.log.exception("Getting project from operational db failed. %s" % identifier)

        if not row:
            return None

        project = {'identifier': row[0],
                   'project_name': MySQLdb.escape_string(row[1]),
                   'author': MySQLdb.escape_string(row[2]),
                   'created': row[3],
                   'updated': row[4],
                   'published': row[5],
                   'project_key': row[6]}

        return project
    def from_analytical(self, identifier):
        """ Return project from analytical database
        """
        query = """
        SELECT identifier, project_name, author, created,
               updated, published, project_key
        FROM project_dim
        WHERE identifier = '%s' AND VALID_TO IS NULL""" % identifier

        row = []
        with analytical_query() as cursor:
            try:
                cursor.execute(query)
                row = cursor.fetchone()
            except:
                conf.log.exception("Getting project from analytical db failed. project identifier : %s" %
                                        identifier)

        if not row:
            return None

        project = {'identifier': MySQLdb.escape_string(row[0]),
                   'project_name': MySQLdb.escape_string(row[1]),
                   'author': MySQLdb.escape_string(row[2]),
                   'created': row[3],
                   'updated': row[4],
                   'published': row[5],
                   'project_key': row[6]}
        return project
def LogTrace(iso, host, mti, result):

    d = datetime.now()
    hex_dump = dumphex(iso.getNetworkISO())
    iso_dump = iso.dumpFields()

    if result != '':
        trasaction_result = ASResponseCodes.GetISOResponseText(result)
    else:
        trasaction_result = ''

    transaction_type = Tran_Type.GetMessagesescription(mti)

    sql = """ INSERT INTO switch_office.host_trace_log(
                        created,
                        host_data,
                        iso,
                        binary_data,
                        trasaction_result,
                        transaction_type
                        )

            VALUES ("%s", "%s", "%s", "%s", "%s", "%s")
          """ % (d, host, MySQLdb.escape_string(iso_dump), MySQLdb.escape_string(hex_dump), trasaction_result, transaction_type)
    return sql
Exemple #10
0
def register():
    page = 'Register'
    global currentUser
    global loggedIn
    db = complimentutil.db_connect()
    cur = db.cursor(cursorclass=MySQLdb.cursors.DictCursor)
    # if user typed in a post ...
    if request.method == 'POST':
      print "HI"
      username = MySQLdb.escape_string(request.form['username'])
      currentUser = username
      pw = MySQLdb.escape_string(request.form['pw'])
      
      query = "INSERT INTO users (username) VALUES ('%s')" % username
      print query
      cur.execute(query)
      
      qy = "INSERT INTO user_passwords (password) VALUES (SHA2('%s', 0))" % pw
      print qy
      cur.execute(qy)
      
      session['username'] = currentUser         
      q = "SELECT * from users WHERE username = '******'" % session['username']
      print q
      cur.execute(q)          
      loggedIn=True
      return redirect(url_for('mainIndex'))
      
    return render_template('register.html', page=page, loggedIn=loggedIn)
Exemple #11
0
def fpost():
    post = MySQLdb.escape_string(smart_str(request.form['post_text']))
    user = MySQLdb.escape_string(smart_str(request.form['user']))
    lv = MySQLdb.escape_string(smart_str(request.form['lvalue']))
    la = MySQLdb.escape_string(smart_str(request.form['ladr']))
    pic = request.files['file']
    if pic:
        ur = secure_filename(pic.filename)
        if '.' not in ur:
            ur = "." + ur
        if len(get_post_all(user)) > 0:
            ur = str(get_post_all(user)[-1][0] + 1) + ur
        else:
            ur = "1" + ur
        pic.save(os.path.join(app.config['UPLOAD_FOLDER'], ur))
        ur = "pics/" + ur
    else:
        ur = "__empty__"
    if posting(user, MySQLdb.escape_string(post), ur):
        if la:
            if la[:7] != "http://":
                la = "http://" + la
            pi = int(get_post_all(user)[-1][0])
            if lv:
                put_link(pi, la, lv)
            else:
                put_link(pi, la)
        session['user'] = user
        return redirect(url_for("hom"))
def insert_course(con, name, course_code, level, program_code):
    """Insert the course in the database given the database.
    """
    course_id = get_course_id(con, name)
    if course_id == 0:
        faculty_id = insert_faculty(con, program_code)
        try:
            cur = con.cursor()
            cur.execute("""INSERT INTO courses 
                           (
                                name, 
                                course_code, 
                                level, 
                                facultyId
                            ) 
                            VALUES 
                            (
                                '%s', '%s', 
                                '%s', %d
                            )""" 
                            % ( mdb.escape_string(name), 
                                mdb.escape_string(course_code), 
                                mdb.escape_string(level), 
                                faculty_id))
            course_id = cur.lastrowid
            con.commit()
        except mdb.Error, e:
            print "Error %d: %s" % (e.args[0], e.args[1])
Exemple #13
0
def estateadd2():
    db = utils.db_connect()
    cur = db.cursor()    

    if request.method == 'POST':       #if user has submitted something
      
      if 'address' in request.form:  #if user is adding an estate
        damageType = MySQLdb.escape_string(request.form['damageType'])
        address = request.form['address']
        query = "INSERT INTO basicHouse (address,county,state,price) VALUES ('" + address +"', '"+MySQLdb.escape_string(request.form['county'])+"', '"+MySQLdb.escape_string(request.form['state'])+"', "+MySQLdb.escape_string(request.form['price'])+")"
        print(query)
        cur.execute(query)
        db.commit()
        query = "INSERT INTO house_damages (type,house_id,cost) VALUES ('"
        query+=damageType+"', (SELECT house_id FROM basicHouse WHERE address= '"+ address+"' GROUP BY address) , '"+ MySQLdb.escape_string(request.form['damageCost']) + "');" 
        print(query)
        cur.execute(query)
        #rows = cur.fetchall()
        db.commit()
        
      if 'damAddress' in request.form: #if adding damages to existing estate
        address = MySQLdb.escape_string(request.form['damAddress'])
        damageType = MySQLdb.escape_string(request.form['damDamageType'])
        damageCost = MySQLdb.escape_string(request.form['damDamageCost'])
        query = "INSERT INTO house_damages (house_id,type,cost) VALUES ((SELECT house_id FROM basicHouse WHERE address = '" + address + "'),'"+ damageType+"',"+damageCost + ");" 
        print(query)
        cur.execute(query)
        db.commit()
        
    return render_template('index.html', name = currentUser)
Exemple #14
0
def author_insert(cursor, last, first, initials):
    """docstring for author_lookup(conn, last, first, initials)"""

    initials_quoted = "NULL"
    first_initial_quoted = "NULL"
    second_initial_quoted = "NULL"

    if len(initials) == 0:
        initials = first[0].upper()

    if len(initials) > 0:
        initials_quoted = "'%s'" % MySQLdb.escape_string(initials)
        first_initial_quoted = "'%s'" % MySQLdb.escape_string(initials[0])

    if len(initials) > 1:
        second_initial_quoted = "'%s'" % MySQLdb.escape_string(initials[1])
    
    last_quoted = "'%s'" % MySQLdb.escape_string(last)
    first_quoted = "'%s'" % MySQLdb.escape_string(first)

    values = (last_quoted, first_quoted, initials_quoted, first_initial_quoted, second_initial_quoted)
    query = """INSERT into author values (NULL, %s, %s, %s, %s, %s);""" % values
    cursor.execute(query)
    cursor.execute("SELECT LAST_INSERT_ID();")
    row = cursor.fetchone()
    author_id = int(row[0])
    
    return author_id
Exemple #15
0
def register():
  #If they registered for an account
  if request.method == 'POST':
    
    #set up database connections
    db = utils.db_connect()
    cur = db.cursor(cursorclass=MySQLdb.cursors.DictCursor)
    
    #get form results.
    username = MySQLdb.escape_string(request.form['username'])
    password = MySQLdb.escape_string(request.form['pw'])
    zipcode = MySQLdb.escape_string(request.form['zipcode'])
    
    #testing in terminal
    print "Hi " + username + " " + password + " " + zipcode
    
    #Insert into 'users' table
    #query = "INSERT INTO users (username, password, zipcode) VALUES ('";
    #query += request.form['username'] + "','" + request.form['pw'] + "','" + request.form['zipcode'] + "')"
    #Hash it
    ###ADD ZIPCODE TO USERS TABLE  
    query = "INSERT INTO users (username, password, zipcode) VALUES ('%s', SHA2('%s', 0), '%d')" % (username, password, int(zipcode))
    print query          #testing in terminal
      
    cur.execute(query)
    db.commit()
    
    return render_template('login.html', selectedMenu='Login')
  
  return render_template('register.html', selectedMenu='Register', name = currentUser)
Exemple #16
0
def login():
    page = 'Login'  
  
    global currentUser
    global loggedIn
    db = complimentutil.db_connect()
    cur = db.cursor(cursorclass=MySQLdb.cursors.DictCursor)
    # if user typed in a post ...
    if request.method == 'POST':
      print "HI"
      username = MySQLdb.escape_string(request.form['username'])
      currentUser = username
      
      pw = MySQLdb.escape_string(request.form['pw'])
      query = "SELECT u.username, up.password FROM users u INNER JOIN user_passwords up ON u.id = up.id WHERE u.username = '******' AND up.password = SHA2('%s', 0)" % (username, pw)
      print query
      cur.execute(query)
           
      if cur.fetchone():
         session['username'] = currentUser                  
         loggedIn=True
         return redirect(url_for('mainIndex'))
      else:
        print "mistake"
    return render_template('login.html', page=page, loggedIn=loggedIn)
Exemple #17
0
        def stringify_for_sql(i, this_type=None):
            """stringify, SQL-escape an object, adding quotes if it is a string"""
            if isinstance(i, basestring):
                if isinstance(i, unicode):
                    try:
                        i = i.encode(encoding)
                    except UnicodeEncodeError:
                        i = unicodedata.normalize('NFKD', i).encode(encoding, 'ignore')

                if dbconnection:
                    i = dbconnection.escape_string(i)
                else:
                    import MySQLdb
                    MySQLdb.escape_string(SQL)

            if isinstance(i, basestring):
                i = "'" + str(i) + "'"
            else:
                try:
                    if i is None or np.isnan(i):
                        i = 'NULL'
                except TypeError:
                    pass
                i = str(i)

            return i
def BuildISOUpdateFieldAndValues(uuid, iso, extra=None):

    if not extra: extra = {}
    v1 = iso.getBitsAndValues()
    field_list = ''

    fields_in_row = 0
    for v in v1:

        try:
            field_name = ISO8583_to_DB[v['bit']]
            if field_list != '':
                fields_in_row += 1
                field_list += ' , '
            # Add a new line every 5 fields.
            if fields_in_row >= 5:
                field_list += '\n  '
                fields_in_row = 0
            field_list += field_name + '="' + MySQLdb.escape_string(v['value']) + '"'
        except KeyError as e:
            print 'Bit does not exist in the database: ' + str(e)

    for extra_field in extra.keys():
        #field_list += ',\n  %s' % extra_field
        v = str(extra[extra_field])
        field_list +=  ", " + extra_field + '="' + MySQLdb.escape_string(v) + '"'

    sql = "UPDATE core_node SET "
    sql +=  field_list
    sql += " WHERE tran_gid " + '="' + uuid + '"'

    return sql
Exemple #19
0
def fun():
    user = MySQLdb.escape_string(smart_str(request.form['user']))
    unf = MySQLdb.escape_string(smart_str(request.form['unf']))
    if unfollow(user, unf):
        posts = fget_post_all(user)
        return render_template("home.html", posts=posts, Username=user)
    return render_template("main-page.html")
Exemple #20
0
def insertMySQL(tweetDict):
    con = None
    try:
        con = mdb.connect('localhost', 'root', 'sa', 'tweetsearch');
        cur = con.cursor()
        with con:
            cur = con.cursor()
            checkquery = "SELECT * FROM tweet WHERE username = '******' AND tweetcontent = '" \
                            + MySQLdb.escape_string(tweetDict.get(tweetDict.keys()[0])) \
                            +"'"
            cur.execute(checkquery)
            rows = cur.fetchall()
            if(len(rows) == 0):
                query = "INSERT INTO tweet(username, tweetcontent) VALUES('" \
                        + MySQLdb.escape_string(tweetDict.keys()[0]) \
                        + "', '" \
                        + MySQLdb.escape_string(tweetDict.get(tweetDict.keys()[0])) \
                        + "')"
                cur.execute(query)
                return True
    except mdb.Error, e:
        print "Error %d: %s" % (e.args[0],e.args[1])
        sys.exit(1)
Exemple #21
0
    def get_qsyk_and_insert(self, docid):
        cover_img = MySQLdb.escape_string(docid['cover_img'])
        docid = docid['docid']

        if self.db_has_exist(docid):
            return

        url = "http://c.3g.163.com/nc/article/%s/full.html" % str(docid)
        data = utils.download_page(url, True)

        if data:
            data = data[docid]
            if data:
                ptime = data['ptime']
                today = ptime.split(' ')[0]
                imgs = data['img']
                body = data['body'].encode('utf-8')

                title = data['title'].replace(' ', '').replace('(', '-').replace('(', '-').replace(')', '').replace(')', '')

                for img in imgs:
                    body = body.replace(img['ref'], "<img src=\"" + img['src'] + "\"/><hr>")

                body = body.replace('%', '%%')
                body = MySQLdb.escape_string(body)
                sql = "insert into wangyi(item_type, title, url, docid, cover_img, ptime, today, body) values('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % (self._item_type, title, url, docid, cover_img, ptime, today, body)
                utils.insert_mysql(sql)
Exemple #22
0
def register(req,context):
    username = MySQLdb.escape_string(req['username'])
    nickname = MySQLdb.escape_string(req['nickname'])
    password = MySQLdb.escape_string(req['password'])
    studentNo = MySQLdb.escape_string(req['studentNo'])
    db = MySQLdb.connect("localhost","root","jcyk","beta")
    cursor = db.cursor()
    #
    sql = "insert into USER (_username,_nickname,_password,_studentNo,_version) values(%s,%s,%s,%s,%s)"
    try:
        cursor.execute(sql,(username,nickname,password,studentNo,1))
        db.commit()
        db.close()
        res = {}
        res['type'] = 'register_result'
        res['body'] = 'ok'
        if(req.has_key('head')):
            filename = '%s.png'%username
            ls_f = base64.b64decode(req['head'])
            f = open(filename,'wb')
            f.write(ls_f)
            f.close()
        return json.dumps(res)
    except:
        db.rollback()
        db.close()
        res = {}
        res['type'] = 'register_result'
        res['body'] = 'error'
        return json.dumps(res)
Exemple #23
0
def login(req,context):
    username = MySQLdb.escape_string(req['username'])
    password = MySQLdb.escape_string(req['password'])
    db = MySQLdb.connect("localhost","root","jcyk","beta")
    cursor = db.cursor()
    #
    sql = "select _password from USER WHERE _username = %s"
    try:
        cursor.execute(sql,(username,));
        result = cursor.fetchone()
        if result[0] != password:
            db.close()
            res = {}
            res['type'] = 'login_result'
            res['body'] = 'error: wrong password'
            return json.dumps(res)
    except:
        db.close()
        res= {}
        res['type'] = 'login_result'
        res['body'] = 'error: no such user'
        return json.dumps(res)
    res= {}
    res['type'] = 'login_result'
    res['body'] = 'ok'
    return json.dumps(res)
    def web_db_insert(self,item):
        #     try:
        #         db.insert('t_hh_dianping_tuangou_deal_info',**data)
        #     except:
        #         pass
        key_str = ','.join('`%s`' % k for k in item.keys())
        value_str = ','.join(
            'NULL' if v is None or v == 'NULL' else "'%s'" % MySQLdb.escape_string('%s' % v) for v in
            item.values())
        kv_str = ','.join(
            "`%s`=%s" % (k, 'NULL' if v is None or v == 'NULL' else "'%s'" % MySQLdb.escape_string('%s' % v))
            for (k, v)
            in item.items())
        # print kv_str
        # print key_str

        sql = "INSERT INTO t_hh_dianping_shop_info_pet_hospital(%s) VALUES(%s)" % (key_str, value_str)
        sql = "%s ON DUPLICATE KEY UPDATE %s" % (sql, kv_str)
        print sql
        # with open('eeeeddddd','a') as f:
        #     f.write(sql+'\n')
        # time.sleep(100)
        try:
            db.query(sql.replace('NULL','0'))
        except:
            pass
Exemple #25
0
def signin():
    user = MySQLdb.escape_string(smart_str(request.form['Username']))
    password = MySQLdb.escape_string(smart_str(request.form['Password']))
    if sign_in(user, password):
        posts = fget_post_all(user)
        return render_template("home.html", posts=posts, Username=user)
    return render_template("main-page.html")
Exemple #26
0
def populateTempHQ(hqDB):
    f = open('shops007.txt')
    string = f.readlines()
    decoded = json.loads(string[0])
    shopdetails = decoded['shopdetails']
    staffdetails = decoded['staffdetails']
    products = decoded['products']
    shopinventories = decoded['shopinventories']
    members = decoded['members']
    for i in shopdetails:
        if(i):
            query = 'insert into hq_shops values("%s","%s","%s",%s)' %(MySQLdb.escape_string(i['shop_Id']),MySQLdb.escape_string(i['name']),MySQLdb.escape_string(i['address']),i['phone_number'])
            hqDB.execute(query)
    for i in staffdetails:
        if(i):
            query = 'insert into hq_staff values(%s,"%s","%s","%s","%s",%s,"%s","%s")' %(i['staff_Id'],MySQLdb.escape_string(i['name']),MySQLdb.escape_string(i['address']),i['gender'],i['DOB'],i['contact'],i['position'],i['shop_Id'])
            hqDB.execute(query)
    for i in products:
        if(i):
            query = 'insert into hq_products values("%s","%s","%s","%s",%s,%s,%s,%s,%s,%s,%s)' %(i['barcode'],MySQLdb.escape_string(i['name']),MySQLdb.escape_string(i['category']),MySQLdb.escape_string(i['manufacturer']),(i['product_type']),i['bundle_unit_qty'],i['bundle_unit_discount'],i['min_stock_level'],i['max_stock_level'],i['normal_price'],i['member_price'])
            hqDB.execute(query)
    for i in shopinventories:
        if(i):
            query = 'insert into hq_shop_inventories values("%s","%s",%s,%s)' %(i['shop_Id'],i['barcode'],i['active_price'],i['quantity'])
            hqDB.execute(query)
    for i in members:
        if(i):
            query = 'insert into hq_members values("%s","%s","%s",%s)' %(MySQLdb.escape_string(i['email']),MySQLdb.escape_string(i['name']),i['password'],i['phone'])
            hqDB.execute(query)
Exemple #27
0
 def sql(self, quoted=True):
     """ gives sql string format, including quotes 
 """
     if quoted:
         return '"%s"' % MySQLdb.escape_string(str(self.data))
     else:
         return '%s' % MySQLdb.escape_string(str(self.data))
Exemple #28
0
    def post(self):
        title = self.get_argument('title', None)
        if not title:
            tid = self.get_argument('tid', None)
            if not tid:
                return self.render('error.html', msg='no id')
            done = self.get_argument('done', None)
            if done:
                self.db.update_task(tid=tid, done=done)
                return self.render('success.html')
            
            content = self.get_argument('content', None)
            if content:
                self.db.update_task(tid=tid, content="'%s'"%MySQLdb.escape_string(content.encode('utf-8')))
                return self.render('success.html')

            order = self.get_argument('order', None)
            if order:
                self.db.update_task(tid=tid, ord=self.db.min_task_ord().get('ord', 0)-1)
                return self.render('success.html')
            
        if self.db.find_task(title): #dump task
            return self.render('error.html', msg='Dump')
        else:# create task
            self.db.create_task(
                    int(time.time()),
                    self.db.max_task_ord().get('ord', 0) + 1,
                    MySQLdb.escape_string(title.encode('utf-8')),
                    '',
                    0,
                    )
            return self.render('success.html')
Exemple #29
0
 def insert_counterfeit_pic(self, phishing_url, img_path):
     '''
     向mysql counterfeit_list表中插入仿冒网站的截图
     '''
     url_hash = hash_md5(phishing_url)
     with open(img_path) as f:
         img = f.read()
     table_name = 'counterfeit_list'
     fields = ['url']
     wheres = {'hash': [url_hash, 's']}
     select_result = self.require_get(
         table_name, fields, wheres, get_type='select', fetch_type='one', print_none=0)
     try:
         # can't use the above definition of the structure of the SQL
         # statement methods, beyond the length
         if select_result is False:
             sql = "INSERT INTO counterfeit_list (url,hash,webpage) VALUES ('%s','%s','%s')" % (
                 phishing_url, url_hash, MySQLdb.escape_string(img))
             self.cur.execute(sql)
             self.db_conn.commit()
         else:
             sql = "UPDATE counterfeit_list SET webpage='%s' WHERE hash='%s'" % (
                 MySQLdb.escape_string(img), url_hash)
             self.cur.execute(sql)
             self.db_conn.commit()
         return True
     except MySQLdb.Error, e:
         re_connect_result = self.check_mysql_error(e)
         if re_connect_result is True:
             return self.insert_counterfeit_pic(phishing_url, img_path)
         else:
             return False
Exemple #30
0
def changePDU(index,barcode,localDB):
    index = "" + str(index)
    if(not(index.isdigit())):
        return "Invalid Index Entered."
    barcode = "" + str(barcode)
    if(not(barcode.isdigit())):
        return "Invalid barcode Entered."
    query0 = "Select count(*) from product_information where barcode = '%s'" % MySQLdb.escape_string(str(barcode))
    localDB.execute(query0)
    result = localDB.fetchone()
    if(result[0] == 0):
        return "Barcode not found."
    message = '1'
    query = "Select count(*) from pdu where pdu_index = %s" % MySQLdb.escape_string(str(index))
    localDB.execute(query)
    result = localDB.fetchone()
    if(result[0] == 0):
        query2 = "Insert into pdu values(%s,'%s')" %(MySQLdb.escape_string(str(index)),MySQLdb.escape_string(str(barcode)))
        result = localDB.execute(query2)
        if not result:
            return ""
    else:
        query2 = "Update pdu set barcode = '%s' where pdu_index = %s" %(MySQLdb.escape_string(str(barcode)),MySQLdb.escape_string(str(index)))
        result = localDB.execute(query2)
        if not result:
            return ""
    return message
def translateBlock(block):
    global iBlockInsert, insertSQLTrans, loadSQL, langTo, loadSQL
    try:
        translate = translator.translate(block[2].encode('utf-8'),
                                         lang_from=fromLang,
                                         lang_to=langTo)
        if translate:
            sql = "({id}, {language_id}, '{text}', NOW(), NOW(), 1, {siteID}, {cc}, 1, 0, 0)".format(
                id=block[0],
                language_id=langID,
                siteID=siteID,
                text=MySQLdb.escape_string(str(translate.encode('utf-8'))),
                cc=len(translate.split()))
        else:
            sql = "({id}, {language_id}, '', NOW(), NOW(), 1, {siteID}, 0, 1, 0, 0)".format(
                id=block[0], language_id=langID, siteID=siteID)
        loadSQL.append(insertSQLTrans + sql + ";")
    except Exception as exc:
        pass
Exemple #32
0
    def insert(self, sql, values):
        self.sql = sql % values
        vs = []
        strtype = type('str')
        for v in values:
            if type(v) == strtype:
                vs.append(MySQLdb.escape_string(v))
            else:
                vs.append(v)

        # print tuple(values);
        # print tuple(vs);exit()
        sql = sql % tuple(vs)
        try:
            self._checkConn()
            self.cur.execute(sql)
            re = True
        except Exception, e:
            re = str(Exception) + ':' + str(e) + ' -- sql:' + sql
Exemple #33
0
 def fetch_recent_task_durations(self, tasks):
     """For each task, determine the duration of its last completed run.
 This is possibly inaccurate, since it identifies a task purely based
 on its description."""
     if len(tasks) == 0:
         return {}
     # Need to manually construct the values for WHERE IN clause, no support from MySQLdb
     escaped_descs = [
         "'" + str(MySQLdb.escape_string(task.description)) + "'"
         for task in tasks
     ]
     where_values = ', '.join(escaped_descs)
     # Fetch duration of last completed run from the dist_test_durations table
     query = """
   SELECT description, duration_secs FROM dist_test_durations
   WHERE description in (%s);
 """ % (where_values)
     c = self._execute_query(query)
     return c.fetchall()
Exemple #34
0
def translateBlock(block):
    global iBlockInsert, insertSQLTrans, loadSQL, langTo
    translate = translator.translate(block[2].encode('utf-8'),
                                     lang_from=fromLang,
                                     lang_to=langTo)
    loadSQL.append(
        "({id}, {language_id}, '{text}', NOW(), NOW(), 1, 1, {cc}, 1)".format(
            id=block[0],
            language_id=langID,
            text=MySQLdb.escape_string(str(translate.encode('utf-8'))),
            cc=len(translate.split())))
    iBlockInsert += 1

    if len(loadSQL) >= maxBlockInsert:
        cursor = db.cursor()
        iBlockInsert = 0
        cursor.execute(insertSQLTrans + ','.join(loadSQL) + ";")
        cursor.close()
        loadSQL = []
Exemple #35
0
    def get_yy_red(self):
        self.tools.setup_logging(sys.argv[1], True, True)
        quncms_db = self.config['mysql']['quncms']
        mysql = sMysql(quncms_db['host'], quncms_db['user'], quncms_db['password'], quncms_db['dbname'])

        links = [
            'http://www.yy.com/t/red',
            #'http://www.yy.com/ent/dance',
            #'http://www.yy.com/ent/music'
        ]

        for i in range(0, len(links)):
            url = links[i]
            html = self.sGet(url, 'utf-8')
            titles = self.sMatch('<p class="video-title">', '<\/p>', html, 0)
            count = self.sMatch('<div class="audience-count">', '<\/div>', html, 0)
            pics = self.sMatch('data-original="', '"', html, 0)
            #3086431716
            gourl = self.sMatch('class="video-box" href="', '"', html, 0)

            for j in range(0, len(titles)):
                _vvid = gourl[j].split('_')
                if len(_vvid) < 2:
                    continue
                axd = self.tools.strip_tags(count[j])
                axd = axd.strip()
                item = {
                    'yy_title': MySQLdb.escape_string(titles[j]),
                    'yy_view': axd,
                    'yy_pic': pics[j],
                    'yy_id': _vvid[1],
                }

                _has = mysql.fetch_one("select * from  video_yy where yy_id=%s" % item['yy_id'])
                if _has is None:
                    action = 'Add'
                    mysql.dbInsert('video_yy', item)
                else:
                    action = 'Update'
                    up = {'yy_title': item['yy_title'], 'yy_view': item['yy_view']}
                    mysql.dbUpdate('video_yy', up, "yy_id=%s" % item['yy_id'])

                logging.debug('%s=====:%s=====%s ' % (action, item['yy_title'], gourl[j]))
Exemple #36
0
def query_preprocessing(query):
    '''preprocessing the query to prevent sql injection'''
    black_words = ['select', 'insert', 'update', 'drop', 'source', 'join']
    black_symbals = [';']

    def gen_re_string(string):
        s = '\\s'
        for i in str(string):
            s += '[' + i + i.upper() + ']'
        s += '\\s'
        return s

    for i in black_words:
        if re.findall(gen_re_string(i), query):
            raise Exception, "query contains illegal word '" + i + "'"
    for i in black_symbals:
        if re.findall(i, query):
            raise Exception, "query contains illegal symbal '" + i + "'"
    return mysql.escape_string(query)
Exemple #37
0
    def sqliterator(self):
        header = """INSERT INTO `amazon`.`book` (
        `id` ,
        `isbn` ,
        `title` ,
        `friendly_title` ,
        `creator` ,
        `contributor` ,
        `language` ,
        `subject` ,
        `publisher`
        )
        VALUES ("""

        tail = ');\n'
        id = self.getID()
        isbn = self.getISBN()
        pub = self.getPublisher()
        result = ""
        if self.switch:
            for title in self.getTitle():
                for ftitle in self.getFriendlyTitle():
                    for creator in self.getCreator():
                        for contrib in self.getContributor():
                            for lang in self.getLanguage():
                                for sub in self.getSubject():
                                    result = result + header
                                    result = result + "'" + id + "'," + str(
                                        isbn) + ","
                                    result = result + "'" + MySQLdb.escape_string(
                                        remove_newline(title)
                                    ) + "'," + "'" + MySQLdb.escape_string(
                                        remove_newline(ftitle)) + "',"
                                    result = result + "'" + MySQLdb.escape_string(
                                        remove_newline(creator)
                                    ) + "'," + "'" + MySQLdb.escape_string(
                                        remove_newline(contrib)) + "',"
                                    result = result + "'" + MySQLdb.escape_string(
                                        remove_newline(lang)
                                    ) + "'," + "'" + MySQLdb.escape_string(
                                        remove_newline(sub)
                                    ) + "'," + "'" + MySQLdb.escape_string(
                                        remove_newline(pub)) + "'"
                                    result = result + tail
                                    yield result
Exemple #38
0
    def __add_model(self, model):
        """モデルをCSV文字列に変換.
        """
        model_cls = model.__class__
        cls_name = model_cls.__name__

        tar_model_table = self.__model_table.get(cls_name, None)
        if tar_model_table is None:
            # 新規登録.
            self.__model_table[cls_name] = ''
            # モデルのクラスを登録.
            if self.__cls_table.get(cls_name) is None:
                self.__cls_table[cls_name] = model_cls
                self.__cls_name.append(cls_name)

        csv_data_list = []
        for field in model_cls._meta.fields:
            # フィールドに設定されている値.
            value = getattr(model, field.attname)
            if isinstance(field, ObjectField):
                value = field.get_db_prep_save(value, None)

            if value is None:
                value = 'NULL'
            elif isinstance(value, datetime.datetime):
                value = "%04d-%02d-%02d %02d:%02d:%02d" % (
                    value.year, value.month, value.day, value.hour,
                    value.minute, value.second)
            elif isinstance(value, bool):
                value = int(value)
            elif isbasestring(value):
                # 無理やりだけどバイナリデータをエスケープ.
                value = MySQLdb.escape_string(StrUtil.to_s(value))
            csv_data_list.append('"%s"' % value)

        # 書き込む.
        csv_text = ModelCSVManager.STR_KUGIRI.join(csv_data_list) + '\r\n'
        self.__model_table[cls_name] += csv_text
        if ModelCSVManager.SIZE_MAX <= len(self.__model_table[cls_name]):
            return True
        else:
            return False
Exemple #39
0
def api_handler(data, api_info):
    """
    @author Blakely Madden
    @date 2014-02-24
    @updated 2014-03-19
    @purpose take the raw request and sanitize it for use with the DB
    @args data [string], api_info [APIInfo]
    @return dictionary
    @exceptions None
    @can_block False
    """
    # remove whitespace and trailing '/'
    # split fields separated by '/' and make a list of them
    info = data.strip()
    info = info.strip('/')
    info = info.split('/')

    for i in info: # escape all the strings for use with SQL statements
        i = MySQLdb.escape_string(i)

    db = db_hooks.DBHook(api_info.host, api_info.port, api_info.user,
                         api_info.pw, api_info.db) # set up the DB connection
    table = info[0]
    try: # get the column data that we need to make JSON objects
        cols = db.execute_db_command("SHOW COLUMNS FROM %s" % table)
    except Exception as e:
        return invalid_request(table, e)

    col_names = [] # pull out the actual column names
    for item in cols:
        col_names.append(item[0])

    if len(info) == 1:
        return safe_db_query_to_json (table_rows (table), col_names, db)
    if len(info) == 2:
        return safe_db_query_to_json (all_values_in_column (table, info[1]),
                                      [info[1]], db)
    if len(info) == 3:
        return safe_db_query_to_json (rows_matching_table_field_val (table,
                                                                     info[1],
                                                                     info[2]),
                                      col_names, db)
Exemple #40
0
def doCrawl(partList, index, logger, id, retry=0):
    #partList = getElementDirt()
    #partList = getElementDirtWithHand()
    try:
        if index > 0:
            partList = partList[index:]
        for ind, part in enumerate(partList):
            tup = checkExitRecord(id, part['pn'])
            if len(tup) == 0:
                logger.info("serach " + part['pn'])
                index = ind
                supplierMap = {}
                supplierArray = getSupplierList(part['id'])
                search = searchPart(part['pn'])
                getElement(search, supplierArray, supplierMap, part['pn'], id,
                           part['id'])
                crawlNextPage(search, supplierArray, supplierMap, part['pn'],
                              id, part['id'])
                foo = [3, 4, 5, 6, 7]
                time.sleep(choice(foo))
            else:
                logger.info(part['pn'] + " had search in a week")
                for row in tup:
                    currentMessage = {}
                    currentMessage['partNumber'] = str(row[0])
                    currentMessage['amount'] = str(row[1])
                    currentMessage['condition'] = str(row[2])
                    currentMessage['supplierCode'] = MySQLdb.escape_string(
                        str(row[3]))
                    currentMessage['foreignKey'] = str(id)
                    currentMessage['commissionElementId'] = part['id']
                    currentMessage['isCopy'] = 1
                    insertStockMarketCrawlMessage(currentMessage)
    except Exception, ex:
        if retry == 1:
            retry = 0
            index = index + 1
        else:
            retry = retry + 1
        logger.error(str(traceback.format_exc()))
        logger.error(str(Exception) + ":" + str(ex))
        doCrawl(partList, index, logger, id, retry)
Exemple #41
0
    def update(self, table, conds, params):
        """
        更新数据
        :arg table 数据表
        :arg conds 更新条件集
        :arg params 更新数据集
        :return 数字(正常) None(异常)
        """
        if isinstance(params, dict) is False:
            return self.update_obj(table, conds, params)

        conds = self.validateConds(conds)
        if conds is None:
            return None

        setValue = ','.join(["{}=%s".format(k) for k in params.keys()])
        values = [MySQLdb.escape_string(str(s)) for s in params.values()]
        str_sql = 'update {} set {} where {}'.format(table, setValue, conds)
        result = self.execute(str_sql, values)
        return result
Exemple #42
0
def InsertJiJiao():
    try:
        update=0;
        url=[["通知新闻","more1.htm"],["公告栏","more2.htm"],["学生工作","more7.htm"],["就业信息","more8.htm"]]
        for i in range(len(url)):
            print url[i][0]        
            content=JiJiao.GetByJiJiao("http://222.195.158.131/jcjxzx/"+url[i][1]);
            length=len(content);
            #print length
            if length<=0:
                update=update+1;
            else:          
                for j in range(length):
                    #print content[j][0],MySQLdb.escape_string(str(content[j][2])),content[j][1]
                    Insert(content[j][0],MySQLdb.escape_string(str(content[j][2])),content[j][1],"基础教学中心",13)
                print time.ctime()+"\t基础教学中心新闻更新数目:"+str(length)
        if update==len(url):
            print time.ctime()+"\t\t暂无更新";
    except  :
        print time.ctime()+"\t基础教学中心更新连接超时。"  
Exemple #43
0
    def insertLdaModel(self, name, value, binary_model):
        "this function insert a row into tv_storage if that row doesnt exist"
        print("hola")
        from mysql.connector import Error
        import MySQLdb
        name = name
        value = value
        try:

            sql = "INSERT INTO prueba (name, lda, binary_model) VALUES (%s,%s,%s);"
            self.cursor = self.connection.cursor()
            self.cursor.execute(
                sql, (name, value, MySQLdb.escape_string(binary_model)))
            #without using commit function is imposible insert but it is not neccesary to do a select
            self.connection.commit()

        except Error as e:
            print("Error", e)
            logging.warning("Error inserting into table prueba model: " +
                            str(name))
Exemple #44
0
def InsertWenXin():
    try:
        update=0;
        url=[["CollegeNews.aspx?news=1","学院新闻"],["CollegeNews.aspx","工作通知"]]
        for i in range(len(url)):
            #print url[i][1]        
            content=WenXin.GetByWenXin ("http://www3.ouc.edu.cn/artcollege/"+url[i][0]);
            length=len(content);
            #print length
            if length<=0:
                update=update+1;
            else:          
                for j in range(length):
                    #print content[j][0],MySQLdb.escape_string(str(content[j][2])),content[j][1]
                    Insert(content[j][0],MySQLdb.escape_string(str(content[j][2])),content[j][1],"文新学院",11)
                print time.ctime()+"\t文新学院新闻更新数目:"+str(length)
        if update==len(url):
            print time.ctime()+"\t\t暂无更新"; 
    except  :
        print time.ctime()+"\t文新学院更新连接超时。"  
Exemple #45
0
    def get_hashlist_id(self):
        ct = formatTime()

        total_size = self.get_bt_size(self.sign_torrent)

        shash = self.sign_torrent['hash']
        sname = self.sign_torrent['name']
        sname = mdb.escape_string(sname)

        info = self.query("select id from pl_hash_list where info_hash='" +
                          shash + "'")
        if len(info) > 0:
            pid = str(info[0][0])
        else:
            print 'insert into pl_hash_list data'
            pid = self.execute(
                "insert into pl_hash_list (`name`,`info_hash`,`length`,`create_time`) values('"
                + sname + "','" + shash + "','" + total_size + "','" + ct +
                "')")
        return pid
Exemple #46
0
    def search_user_by_email(self, email):
        """ Search an user inside SQL Database

        :param email: String with email adddress
        :return: Dict with result of SQL query
        """
        logger.info("Searching for email address {}".format(email))
        email = MySQLdb.escape_string(email)

        query = "SELECT {} FROM {} WHERE {}=%s ORDER BY {} LIMIT 1;".format(
            self.user_column, self.user_table, self.user_email_column,
            self.user_column)

        user_info = self._search(query, email)

        if not user_info:
            raise UserNotFound(
                "User not found in database for email '{}'".format(email))

        return dict(user_info.fetchone())[self.user_column]
def createUser(username, age, gender, height, postal_code):
    print(username, age, gender, height, postal_code)
    #Escapamos el valor del username
    username = MySQLdb.escape_string(username)
    username = username.decode("utf-8")
    #Comprobamos que todos los datos son correctos.
    correctAge = age.isdigit()
    correctGender = (gender == '1' or gender == '0')
    correctHeight = height.isdigit()
    correctPostalCode = postal_code.isdigit()
    if (correctAge and correctGender and correctHeight and correctPostalCode):
        #Si todos los datos son correctos, creamos el objeto y
        #lo subimos a la bbdd.
        SQLSentence = "INSERT INTO Users (username, age, gender, height, postal_code, expenses) VALUES ('{0}', {1}, {2}, {3}, {4}, 0)".format(
            str(username), age, gender, height, postal_code)
        result = insert_sql(SQLSentence)
        return result
    else:
        return False
    return True
Exemple #48
0
def InsertSystemOfCourse():
    try:
        update=0;
        url=[["最新公告","http://jwc.ouc.edu.cn:8080/ouc/index.do"]]
        for i in range(len(url)):
    #        print url[i][0]        
            content=SystemOfCourse.GetByCourse(url[i][1]);
            length=len(content);
    #        print length
            if length<=0:
                update=update+1;
            else:          
                for j in range(length):
                    #print content[j][0],MySQLdb.escape_string(str(content[j][2])),content[j][1]
                    Insert(content[j][0],MySQLdb.escape_string(str(content[j][2])),content[j][1],"选课系统",15)
                print time.ctime()+"\t选课系统公告更新数目:"+str(length)
        if update==len(url):
            print time.ctime()+"\t选课系统公告\t暂无更新"      
    except  :
        print time.ctime()+"\t选课系统更新连接超时。"     
Exemple #49
0
def InsertYiShu():
    try:
        update=0;
        url=[["最新公告","more11.htm"],["系内动态","more1.htm"],["学术交流","more9.htm"]]
        for i in range(len(url)):
    #        print url[i][0]        
            content=YiShu.GetByYiShu("http://222.195.158.131/wanb/"+url[i][1]);
            length=len(content);
    #        print length
            if length<=0:
                update=update+1;
            else:          
                for j in range(length):
                    #print content[j][0],MySQLdb.escape_string(str(content[j][2])),content[j][1]
                    Insert(content[j][0],MySQLdb.escape_string(str(content[j][2])),content[j][1],"艺术系",14)
                print time.ctime()+"\t艺术系新闻更新数目:"+str(length)
        if update==len(url):
            print time.ctime()+"\t\t暂无更新";   
    except  :
        print time.ctime()+"\t艺术系更新连接超时。"  
Exemple #50
0
def encode_post(text):
    '''
    INPUT  : Raw Text (contains html is ok)
    OUTPUT : Fresh Text (MySQL Escaped and Stripped)
    '''
    #    text = text.encode('ascii','ignore').strip()
    try:
        text = text.encode('ascii', 'replace')
    except:
        print '\nDECODE ERROR Encode Post\n' + text
    text = text.strip()
    text = re.sub('\t', '', text)
    text = re.sub('\n', '', text)
    text = re.sub('\r', '', text)
    try:
        text = MySQLdb.escape_string(text)
    except:
        #        hash = hashlib.sha224(text).hexdigest()
        print '\nESCAPE ERROR ENCODE Post\n' + text
    return text
Exemple #51
0
 def add(bank_id, name, rangedate, url, beginDate, endDate):
     try:
         time.strptime(beginDate, "%Y-%m-%d")
         beginDate = "'" + beginDate + "'"
     except:
         beginDate = 'NULL'
     try:
         time.strptime(endDate, "%Y-%m-%d")
         endDate = "'" + endDate + "'"
     except:
         endDate = 'NULL'
     name = MySQLdb.escape_string(name)
     cursor = XykSpider.db().cursor()
     sql = "INSERT INTO s_spider (`bank_id`, `name`, `url`, `range_date`, `begin_date`, `end_date`, `time`) VALUES ( %d, '%s', '%s', '%s', %s,  %s, now())"
     sql = sql % (bank_id, name, url, rangedate, beginDate, endDate)
     try:
         cursor.execute(sql)
     except:
         print sql
     XykSpider.db().commit()
Exemple #52
0
 def select_blog_info(self, BlogId, IsAdmin=None):
     '''
     @summary: 查询当前文件的信息
     '''
     datatuple = ()
     try:
         BlogId = MySQLdb.escape_string(BlogId)
         if IsAdmin:
             sql1 = '''SELECT `GroupCode`,`Subject`,`FileName`,`AddTime`,`Views`,`Privacy` FROM `BlogData` WHERE Id = %s AND IsDelete = 0;''' % BlogId
         else:
             sql1 = '''SELECT `GroupCode`,`Subject`,`FileName`,`AddTime`,`Views`,`Privacy` FROM `BlogData` WHERE Id = %s AND IsDelete = 0 AND Privacy = 0;''' % BlogId
         sql2 = '''UPDATE `BlogData` SET Views = Views + 1 WHERE `Id` = %s''' % BlogId
         self.MySQLAccess.execute(sql2)
         data = self.MySQLAccess.select(sql1)
         if data:
             datatuple = data[0]
     except:
         err_msg = get_err_msg()
         root.error(err_msg)
     return datatuple
Exemple #53
0
    def __init__(self, object):
        self.perfdb = object.perfdb
        self.phase = object.phase
        self.test_dir = object.test_dir
        self.test_short_dir = object.test_short_dir
        self.output_dir = object.output_dir
        self.output_file_name = object.output_file_name
        self.contamination = os.path.join(self.output_dir,
                                          "contamination_message")
        self.contaminated = 1 if os.path.exists(self.contamination) else 0
        self.contamination_message = "No contamination."
        if self.contaminated:
            with open(self.contamination, "r") as f:
                self.contamination_message = MySQLdb.escape_string(
                    f.read().replace('\n', ''))
        self.did_correct_pass = 0
        self.did_time_pass = 0

        self.test_run_model_result = TableRow("test_run_model_result",
                                              self.perfdb)
Exemple #54
0
def InsertShuXue():
    try:
        update=0;
        url=[["http://www2.ouc.edu.cn/math/Ch/main.asp","首页"]]
        for i in range(len(url)):
            #print url[i][1]        
            content=ShuXue.GetByShuXue(url[i][0]);
            length=len(content);
            #print length
            if length<=0:
                update=update+1;
            else:          
                for j in range(length):
                    #print content[j][0],MySQLdb.escape_string(str(content[j][2])),content[j][1]
                    Insert(content[j][0],MySQLdb.escape_string(str(content[j][2])),content[j][1],"数学学院",12)
                print time.ctime()+"\t数学学院新闻更新数目:"+str(length)
        if update==len(url):
            print time.ctime()+"\t\t暂无更新";    
    except  :
        print time.ctime()+"\t数学学院更新连接超时。"  
Exemple #55
0
def pg_search(title, page):
    if page < 0:
        return {}
    start = (page - 1) * 10
    end = 10
    sqlquery = """SELECT DISTINCT `id`, `title` , `creator` , `contributor`
    FROM `book`
    WHERE MATCH (
    title, friendly_title
    )
    AGAINST (
    '""" + MySQLdb.escape_string(title) + """'
    ) ;"""
    db = connect_to_database("amazon", "root",
                             "gitkotwg0")  #replace with password
    cursor = db.cursor()
    cursor.execute(sqlquery)
    result = cursor.fetchall()
    db.close()
    books = {}

    if (start > len(result)):
        start = len(result)
    for i in xrange(start, len(result)):
        if (len(books) == end):
            break
        id, title, creator, contributor = result[i]
        if books.has_key(id):
            if creator:
                books[id]['creator'].append(creator)
            if contributor:
                books[id]['contributor'].append(contributor)
            books[id]['creator'] = unique(books[id]['creator'])
            books[id]['contributor'] = unique(books[id]['contributor'])
        else:
            books[id] = {'title': title, 'creator': [], 'contributor': []}
            if creator:
                books[id]['creator'].append(creator)
            if contributor:
                books[id]['contributor'].append(contributor)
    return books
Exemple #56
0
def getLabourContractList(request):
    usr_id = request.session.get('usr_id','') or testid
    if usr_id ==0:
        s = """
        {
        "errcode": -1,
        "errmsg": "无权访问,请先关注"
        }        """
        return HttpResponseJsonCORS(s)
    #if int(usr_id) == 447:
    #    usr_id = 173
    pageNo = request.POST.get('pageNo','') or 1
    pageNo = int(pageNo)
    search = request.POST.get('search','')
    search = MySQLdb.escape_string(search)
    sql="""select lc.id,op.id,op.cname,lc.Req_no,lc.apply_day from labour_contract lc 
           left join out_proj op on lc.proj_id = op.id
           LEFT JOIN users_wx U ON U.addr_id = lc.teams_id
           left join labour_contract_invalid lci on lc.id = lci.lc_id
           where U.usr_id = %s and lci.id is null
        """%(usr_id)
    print sql
    if search !='':
        sql+="AND ( IFNULL(op.cname,'') LIKE '%%%s%%' OR IFNULL(lc.req_no,'') LIKE '%%%s%%' ) "%(search,search)
    sql+="ORDER BY lc.apply_day DESC"
    rows,iTotal_length,iTotal_Page,pageNo,select_size = db.select_for_grid(sql,pageNo,10)
    names = 'lc_id proj_id proj_name req_no apply_day'.split()
    data = [dict(zip(names, d)) for d in rows]
    L = json.dumps(data,ensure_ascii=False,cls=ComplexEncoder)
    s = """
        {
        "errcode": 0,
        "errmsg": "获取协议列表成功",
        "data":%s,
        "totalLength":%s,
        "totalPage":%s,
        "pageNo":%s,
        "pageSize":%s
        }        """%(L,iTotal_length,iTotal_Page,pageNo,select_size)
    #print ToGBK(s)
    return HttpResponseJsonCORS(s)
Exemple #57
0
def write_to_db(dic):
    db = MySQLdb.connect(host='localhost',
                         user='******',
                         passwd='root',
                         db='en_magic',
                         charset='utf8')
    cursor = db.cursor()
    for v in keys:
        if dic.get(v) == None:
            dic[v] = ''
        else:
            dic[v] = MySQLdb.escape_string(dic[v])
    try:
        pre_sql = "select id from tb_book_pub where isbn = '%s'" % dic['isbn']
        if dic['isbn'] == '':
            pre_sql = "select id from tb_book_pub where url = '%s'" % dic['url']
        if cursor.execute(pre_sql) != 0:
            db.close()
            return
        sql = "insert into tb_book_pub( \
			name, authors, publisher, \
			isbn, url, img_address, \
			price, datePubed, \
			language, format, age_range, \
			pagenum, categories, series) \
			values ('%s', '%s', '%s', \
			'%s', '%s', '%s', \
			'%s', '%s', '%s', \
			'%s', '%s', '%s', \
			'%s', '%s', '%s')"       \
         % (dic['name'], dic['authors'], dic['publisher'], \
         dic['isbn'], dic['url'], dic['img_address'], \
         dic['price'], dic['datePubed'], \
         language, dic['format'], dic['age_range'],
         dic['pagenum'], dic['categories'], dic['series'])
        cursor.execute(sql)
        db.commit()
    except Exception as e:
        print e
        db.rollback()
    db.close()
Exemple #58
0
def run(stage,subject,type):
    with open('subject_list.json','rb') as f:
        subject_list = json.load(f)
    _subject = None
    for sub in subject_list:
        if sub['stage'] == stage and sub['subject'] == subject:
            _subject = sub
    if _subject is None:
        return 
    id_list = get_question_id_list(stage,subject,type)
    for id in id_list:
        if redis.get(id) is None:
            try:
                redis.set(id,0)
                question = get_question(id)
                _question = dict()
                change = False
                for key,value in question.iteritems():
                    url_list = get_replace_str(value)
                    for url in url_list:
                        print url
                    if url_list is not None and len(url_list) > 0:
                        change = True
                    print '=='*30 ,'qlen ', len(value)
                    _question[key] = replace(value,url_list)
                    print '=='*30 ,'_qlen ', len(_question[key])
                    print _question.keys()
                    if _question[key] is not None:
                        _question[key] = MySQLdb.escape_string(_question[key])
                _question['id'] = id
                if change:
                    update_question(_question)
                redis.set(id,1)
                del id
            except Exception as e:
                print 'hi', e
                redis.delete(id)
                del id
#            time.sleep(2)
            if one:
                break
def getValidityResult(field_id, request):
    sql = "select ifnull(validity_sql,''),para_cols from menu_form_validity where field_id= '%s'" % (
        field_id)
    lT, iN = db.select(sql)
    if iN == 0:
        return 1
    sql = lT[0][0]
    para_cols = lT[0][1]
    paras = para_cols.split(',')
    print paras
    print request.POST
    for e in paras:
        if e == '': break
        sql = sql.replace("{%s}" % e,
                          MySQLdb.escape_string(request.POST.get(e, '')))

    print ToGBK(sql)
    lT, iN = db.select(sql)
    if iN == 0:
        return 1
    return lT[0][0]
Exemple #60
0
    def assign_rid_user(self, rid, username):
        """
        Assigns a receipt id (from an existing receipt in the database) to an owner
        :return: (bool) True, if anything ok, False, if receipt already assigned
        """

        self.__CURSOR.execute(
            "SELECT user_id FROM receipts WHERE receipt_id = ('{rid}')".format(
                rid=MySQLdb.escape_string(rid)))
        if self.__CURSOR.fetchone() != (None, ):
            return False

        user_id = self.__get_user_id(username)
        self.__CURSOR.execute(
            "UPDATE receipts SET user_id={uid} WHERE receipt_id='{rid}'".
            format(uid=user_id, rid=rid))
        self.__CONNECTION.commit()
        logging.info(
            "<USER-HANDLER> Receipt -> User\n\t|-USERNAME: {name}\n\t|-USER ID: {id}\n\t"
            "'-RECEIPT ID: {rid}".format(name=username, id=user_id, rid=rid))
        return True