2017-10-15 77 views
-1

我寫了一個簡單的發佈應用程序,連接到一個名爲論壇的數據庫。我的代碼如下。如何使用python漂白庫來避免腳本注入?

# "Database code" for the DB Forum. 

import datetime, psycopg2, bleach 


POSTS = [("This is the first post.", datetime.datetime.now())] 

def add_post(message): 
    ''' This function insert post into the database ''' 
    db = psycopg2.connect(dbname = 'forum') 
    c = db.cursor() 
    c.execute("insert into posts values (%s)", (message,)) 
    db.commit() 
    db.close() 

def get_posts(): 
    '''Take the posts from the databse ''' 
    db = psycopg2.connect(dbname = 'forum') 
    c = db.cursor() 
    c.execute("select content, time from posts order by time") 
    result = c.fetchall() 
    POSTS.extend(result) 
    db.close() 
    return reversed(POSTS) 

我想在此代碼中使用漂白庫。但我不知道如何。我已經輸入漂白劑庫。提前致謝。

+0

不清楚你在問什麼。如果你的問題是'我該如何使用漂白劑庫',它可能對目前的[SO]來說太廣泛和不確定。看一看[ask]和[help/on-topic] – pvg

+0

Bleach在輸出層中是相關的,並且這裏的方法都沒有輸出任何東西。 – MatsLindh

回答

0

您必須添加下面的行放在add_post方法:

text = bleach.clean(str(message)) 

,然後相應地調整執行功能:

c.execute("insert into posts values (%s)", (text,)) 

所以完全add_post方法是這樣的:

def add_post(message): 
    ''' This function insert post into the database ''' 
    db = psycopg2.connect(dbname = 'forum') 
    c = db.cursor() 
    text = bleach.clean(str(message)) 
    c.execute("insert into posts values (%s)", (text,)) 
    db.commit() 
    db.close()