예제 #1
0
파일: util.py 프로젝트: kyleslight/wutong
    def __init__(self, number):
        self.number = number
        self.db = db_test
        self.user = UserModel(self.db)
        self.group = GroupModel(self.db)
        self.article = ArticleModel(self.db)
        self.admin = {
            'email': '*****@*****.**',
            'penname': 'wutong',
            'password': '******',
        }

        self.gen_test_data()
예제 #2
0
파일: publish.py 프로젝트: xia0204/Minos-1
    def post(self, *args, **kwargs):
        id = self.get_body_argument("id", default=None)
        if not id:
            self.custom_error("不存在这篇文章", "", id)
        post = yield self.db.article.find_one({"_id": ObjectId(id)})
        self.__check_power(post)
        content = self.get_body_argument("ckeditor", default=None)
        post["title"] = self.get_body_argument("title", default=None)
        sort = self.get_body_argument("sort", default=None)
        post["charge"] = intval(self.get_body_argument("charge", default=0))
        post["freebegin"] = intval(
            self.get_body_argument("freebegin", default=0))
        post["freeend"] = intval(self.get_body_argument("freeend", default=0))

        if not post["title"]:
            self.custom_error("标题不能为空", content, id)
        if post["charge"] < 0:
            self.custom_error("收费不能低于0", content, id)
        if post["freebegin"] > post["freeend"]:
            self.custom_error("结束时间不能小于开始时间", content, id)
        if not sort:
            self.custom_error("不存在这个分类", content, id)
        post["sort"] = yield self.db.sort.find_one({"_id": ObjectId(sort)})
        if not post["sort"]:
            self.custom_error("不存在这个分类", content, id)

        # filter html
        post["content"] = xss_filter(content)
        model = ArticleModel()
        if not model(post):
            self.custom_error(model.error_msg, content, id)
        yield self.db.article.find_and_modify({"_id": post["_id"]}, post)
        self.redirect("/post/%s" % id)
예제 #3
0
파일: publish.py 프로젝트: joeyxy/Minos
	def post(self, *args, **kwargs):
		content = self.get_body_argument("ckeditor", default=None)
		title = self.get_body_argument("title", default=None)
		sort = self.get_body_argument("sort", default=None)
		charge = intval(self.get_body_argument("charge", default=0))
		freebegin = intval(self.get_body_argument("freebegin", default=0))
		freeend = intval(self.get_body_argument("freeend", default=0))
		if not title:
			self.flash["article"] = content
			self.custom_error("标题不能为空哦", jump = "/publish")
		if charge < 0:
			self.flash["article"] = content
			self.custom_error("收费不能低于0", jump = "/publish")
		if freebegin > freeend:
			self.flash["article"] = content
			self.custom_error("结束时间不能小于开始时间", jump = "/publish")
		if not sort:
			self.flash["article"] = content
			self.custom_error("不存在这个分类", jump = "/publish")
		tosort = yield self.db.sort.find_and_modify({
			"_id": ObjectId(sort)
		}, {
			"$inc": {"article": 1}
		})
		if not tosort:
			self.flash["article"] = content
			self.custom_error("不存在这个分类", jump = "/publish")

		# filter html
		content = xss_filter(content)

		article = {
			"title": title,
		    "content": content,
		    "user": self.current_user["username"],
			"sort": tosort,
		    "view": 0,
		    "like": [],
		    "unlike": [],
		    "charge": charge,
		    "time": time.time(),
		    "freebegin": freebegin,
		    "freeend": freeend,
		    "buyer": [],
		    "thanks": [],
		    "star": False,
		    "rank": 0,
		    "comment": [],
		    "open": False,
		    "top": False,
		    "lastcomment": time.time()
		}
		model = ArticleModel()
		if not model(article):
			self.flash["article"] = content
			self.custom_error(model.error_msg, jump = "/publish")
		id = yield self.db.article.insert(article)
		self.redirect("/post/%s" % id)
예제 #4
0
파일: util.py 프로젝트: kyleslight/wutong
class TestDataGenerator(object):
    def __init__(self, number):
        self.number = number
        self.db = db_test
        self.user = UserModel(self.db)
        self.group = GroupModel(self.db)
        self.article = ArticleModel(self.db)
        self.admin = {
            'email': '*****@*****.**',
            'penname': 'wutong',
            'password': '******',
        }

        self.gen_test_data()

    def initdb(self):
        sql_dir = wutong_path("model/dbschema/")
        paths = ["schema.sql", "function.sql"]
        paths = [(sql_dir + p) for p in paths]

        for path in paths:
            sql = open(path, "r").read()
            assert (self.db.execute(sql))

    def gen_admin_user(self):
        hashuid = self.user.do_register(self.admin['email'],
                                        self.admin['penname'],
                                        self.admin['password'])
        self.admin["uid"] = self.user.do_activate(hashuid)

        # gen avatar
        avatar_dir = os.path.join(os.path.dirname(__file__),
                                  '../static/avatar/')
        random_path = os.path.join(avatar_dir, 'random')
        avatar_path = os.path.join(random_path,
                                   random.choice(os.listdir(random_path)))

        with open(avatar_path, 'r') as avatar_fp:
            avatar = genavatar(avatar_fp, avatar_dir, self.admin['penname'])
            self.user.update_user_avatar_by_penname(self.admin['penname'],
                                                    avatar)

        return self.admin

    def gen_users(self):
        """
        Generate random user from randomuser.me
        """
        url = 'http://api.randomuser.me/?results=%s'
        users = []
        results = []

        for i in xrange(self.number / 5):
            response = requests.get(url % 5)
            results += response.json()['results']
        response = requests.get(url % (self.number % 5))
        results += response.json()['results'] or []

        for res in results:
            user = res["user"]
            user["penname"] = user["name"]["first"] + user["name"]["last"]
            user["password"] = '******'
            user["sex"] = user["gender"]
            user["address"] = user["location"]["city"] + user["location"][
                "state"]
            user["avatar"] = user["picture"]
            user["intro"] = ''.join(
                [str(v) for v in user["location"].values()])
            user["motto"] = ''.join([str(v) for v in user.values()])
            user["age"] = user["location"]["zip"][-2:]
            users.append(user)

        # insert into db
        for user in users:
            hashuid = self.user.do_register(user["email"], user["penname"],
                                            user["password"])
            user["uid"] = self.user.do_activate(hashuid)
            self.user.update_user_avatar_by_penname(user['penname'],
                                                    user['avatar'])

        return users

    def gen_groups(self, users):
        gid = self.group.do_create(self.admin['uid'], 'admin_group')
        gids = [gid]
        for i in xrange(random.randint(1, self.number)):
            user = random.choice(users)
            gid = self.group.do_create(
                user['uid'],
                '%s group by %s' % (random.random(), user['uid']),
                is_public=random.randint(0, 2),
            )
            self.group.do_join_group(gid, self.admin["uid"])
            gids.append(gid)

        return gids

    def gen_random_group_data(self, users, gids):
        tids = []
        cids = []
        bids = []

        def random_reply_id():
            if random_bool():
                try:
                    return random.choice(tids)
                except:
                    pass
            return None

        for gid in gids:
            uid = random.choice(users)['uid']
            self.group.do_join_group(gid, uid)

            tid = self.group.do_create_topic(
                gid, uid, 'random topic in group %s by %s' % (gid, uid),
                '%s' % random.random(), random_reply_id())
            tids.append(tid)

            cid = self.group.do_create_chat(gid, uid,
                                            'random chat in group %s' % gid,
                                            random_reply_id())
            cids.append(cid)

            bid = self.group.do_create_bulletin(
                gid, uid, 'random bulletin in group %s' % gid,
                '%s' % random.random())
            bids.append(bid)

        return tids, cids, bids

    def gen_articles(self, users):
        aids = []

        for i in xrange(random.randint(self.number, self.number * 10)):
            uid = random.choice(users)['uid']
            aid = self.article.do_create(
                uid,
                '%s article title by %s' % (random.random(), uid),
                '<p>random mainbody %s</p>' % random.random(),
                tags=['技术', 'linux', 'python'])
            aids.append(aid)

        return aids

    def gen_random_article_data(self, users, aids):
        for aid in aids:
            for i in xrange(random.randint(0, self.number)):
                uid = random.choice(users)['uid']
                self.article.create_bottom_comment(
                    aid, uid, '%s comment' % random.random())
                paragraph_id = str(random.randint(0, 1))
                self.article.create_side_comment(
                    aid, uid, '%s comment' % random.random(), paragraph_id)

    def gen_test_data(self):
        self.initdb()
        admin = self.gen_admin_user()
        users = self.gen_users()
        gids = self.gen_groups(users)
        tids, cids, bids = self.gen_random_group_data(users, gids)
        aids = self.gen_articles(users)
        self.gen_random_article_data(users, aids)
예제 #5
0
파일: publish.py 프로젝트: yangxue088/Minos
    def post(self, *args, **kwargs):
        content = self.get_body_argument("ckeditor", default=None)
        title = self.get_body_argument("title", default=None)
        sort = self.get_body_argument("sort", default=None)
        charge = intval(self.get_body_argument("charge", default=0))
        freebegin = intval(self.get_body_argument("freebegin", default=0))
        freeend = intval(self.get_body_argument("freeend", default=0))
        private = self.get_body_argument('private', default='off')

        if not title:
            self.flash["article"] = content
            self.custom_error("标题不能为空哦", jump="/publish")
        if charge < 0:
            self.flash["article"] = content
            self.custom_error("收费不能低于0", jump="/publish")
        if freebegin > freeend:
            self.flash["article"] = content
            self.custom_error("结束时间不能小于开始时间", jump="/publish")
        if not sort:
            self.flash["article"] = content
            self.custom_error("不存在这个分类", jump="/publish")
        tosort = yield self.db.sort.find_and_modify({"_id": ObjectId(sort)},
                                                    {"$inc": {
                                                        "article": 1
                                                    }})
        if not tosort:
            self.flash["article"] = content
            self.custom_error("不存在这个分类", jump="/publish")

        # filter html
        content = xss_filter(content)

        # attach file
        attach = []
        fs = motor.motor_tornado.MotorGridFS(self.db)

        for file in self.request.files.get('file', []):
            fs_id = yield fs.put(file['body'], filename=file['filename'])
            attach.append(fs_id)

        article = {
            "title": title,
            "content": content,
            "user": self.current_user["username"],
            "sort": tosort,
            "view": 0,
            "like": [],
            "unlike": [],
            "charge": charge,
            "time": time.time(),
            "freebegin": freebegin,
            "freeend": freeend,
            "buyer": [],
            "thanks": [],
            "star": False,
            "rank": 0,
            "comment": [],
            "open": False,
            "top": False,
            "lastcomment": time.time(),
            'attach': attach,
            'private': private,
        }
        model = ArticleModel()
        if not model(article):
            self.flash["article"] = content
            self.custom_error(model.error_msg, jump="/publish")
        id = yield self.db.article.insert(article)

        # send mail
        users = self.db.member.find()

        article_url = '{}/post/{}'.format(tornado.options.options.url, id)
        content = "{}<br><br>{}".format(
            '''<a href="{}" target="_blank">点击查看论坛文章</a>'''.format(
                article_url), content)

        while (yield users.fetch_next):
            user = users.next_object()

            if user.get('power') >= 0 and self.settings["email"][
                    "method"] == "mailgun" and "email" in user and user.get(
                        "allowemail"):
                Sendemail(self.settings.get("email")).send(
                    title=u"论坛文章:《{}》,作者:{}".format(
                        title, self.current_user["username"]),
                    content=content,
                    to=user["email"])

        self.redirect("/post/%s" % id)