是否有一种方法来限制用户每小时可以发的帖子以避免垃圾邮件?我曾经考虑过基于Cookie或IP地址来制作它,但是我并没有运气找到这种方法的例子。
编辑:我想保持匿名,所以将没有注册用户。
答案 0 :(得分:0)
假设您有一个数据库来存储帖子数据,包括发帖人的姓名和时间戳,则可以创建一个类来确定用户是否在有效时间发帖:
import re, itertools, sqlite3
class Posts:
def __init__(self, _username[str, int], _rate = 5) -> None:
'''rate: number of posts per hour'''
self.username = _username
self.rate = _rate
def __bool__(self):
'''assuming database has columns "author" and "timestamp"
timestamp: mm/dd/yy hh:mm:ss
'''
data = list(sqlite3.connect('filename.db').cursor().execute("SELECT author, timestamp from TABLENAME"))
user_posts = [re.findall('\w+/\w+/\w+\s\d+', b)[0] for a, b in data if a == self.username]
if not user_posts:
return True
groups = [list(b) for _, b in itertools.groupby(user_posts)]
return len(groups[-1]) < self.rate
然后,在应用程序中,使用/post_article
之类的路由:
@app.route('/post_article', methods=['GET', 'POST'])
def post_article():
if flask.request.method == 'POST':
poster = Posts(flask.session['current_user'])
if not poster:
return '<p>Posting limit exceeded. Try again soon</p>'
#take in user form data and update db
return flask.redirect('/new_article_name')
return flask.render_template('post_article.html')