2017-10-15 24 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() 
相关问题