def import_topics(from_cache=False): Topic.query.delete() db.session.commit() if from_cache: with open(os.path.dirname(os.path.realpath(__file__)) + '/../' + settings.TOPIC_DATA_CACHE, mode='r') as cachejson: data = json.load(cachejson) for topic in data: db_first_or_create( Topic, commit=False, name=topic['name'], wikipedia_parent=None if topic['wikipedia_parent'] == '' else topic['wikipedia_parent']) db.session.commit() if not from_cache: Topic.populate_topics_from_phantom_forms() with open(os.path.dirname(os.path.realpath(__file__)) + '/../' + settings.TOPIC_DATA_CACHE, mode='w') as cachejson: json.dump([json.loads(t.json) for t in Topic.query.all()], cachejson, indent=4)
def test_time_type_setting(self): """Tests whether the time type can be set correctly.""" self.post = Post( title="Title", text="Text", user_id=1, topics=[Topic(tag_name="topic1"), Topic(tag_name="topic2")], id=1) # Difference between the two timestamps is in minutes. # So timetype should equal 0. self.post.timestamp = datetime(2018, 6, 29, 10, 00, 00) self.test_timestamp = datetime(2018, 6, 29, 10, 2, 00) self.post.get_minutes(input_time=self.test_timestamp) self.assertEqual(0, self.post.time_type) self.assertFalse(1 == self.post.time_type) # Difference between the two timestamps is in hours. # So timetype should equal 1. self.post.timestamp = datetime(2018, 6, 29, 10, 00, 00) self.test_timestamp = datetime(2018, 6, 29, 11, 2, 00) self.post.get_minutes(input_time=self.test_timestamp) self.assertEqual(1, self.post.time_type) self.assertFalse(2 == self.post.time_type) # Difference between the two timestamps is in hours. # So timetype should equal 1. self.post.timestamp = datetime(2018, 6, 29, 10, 00, 00) self.test_timestamp = datetime(2018, 6, 30, 11, 2, 00) self.post.get_minutes(input_time=self.test_timestamp) self.assertEqual(2, self.post.time_type) self.assertFalse(1 == self.post.time_type)
def initdb(): """Initialize MySQL databse.""" from app.libs.db import init_db from app.models import Permission, User, Topic from app.base.roles import Roles from app.settings import Admins, Topics from app.libs.utils import encrypt_password click.echo('[2L] {0}..'.format(initdb.__doc__)) init_db() click.echo('\n\n[2L] init permisions...') for attr, role in Roles.__dict__.items(): if (not attr.startswith('__') and '{0}' not in role and role != 'root'): click.echo(' -> {0}'.format(role)) Permission.create(role) click.echo('\n\n[2L] init master chief...') bit_sum = Permission.root_permission() for admin in Admins: click.echo(' -> {0}'.format(admin)) if admin['role'] == 'root': admin['role'] = bit_sum else: admin['role'] = (Permission.get_by_role(admin['role']).bit | Permission.get_by_role('comment').bit | Permission.get_by_role('vote').bit) admin['password'] = encrypt_password(admin['password']) User.create(**admin) click.echo('\n\n[2L] create default topics...') for topic in Topics: click.echo(' -> {0}'.format(topic)) Topic.create(**topic)
def setUp(self): super(TopicsTests, self).setUp(self) self._me = USER self._topic = TOPIC self._topic.update({'admin_id': 1}) User.create(**self._me) Topic.create(**self._topic)
def post(self, topic_id): name = self.get_argument('name', None) description = self.get_argument('description', None) rules = self.get_argument('rules', None) avatar = self.get_argument('avatar', None) why = self.get_argument('why', None) if not all([name, description, rules, why]): raise exceptions.EmptyFields() else: exists = yield gen.maybe_future(Topic.get_by_name(name)) if exists: raise exceptions.TopicNameAlreadyExists() else: created_user = self.current_user topic = yield gen.maybe_future( Topic.create(name, created_user, avatar, description, rules, why)) # Update Gold. update_gold.apply_async(('new_proposal', created_user)) # Update proposal state. seconds = Level['time']['proposal'] wait = datetime.now(get_localzone()) + timedelta(seconds=seconds) check_proposal.apply_async((topic.id,), eta=wait)
def deploy(): """运行部署任务""" from flask.ext.migrate import upgrade upgrade() Role.insert_roles() City.insert_cities() Topic.insert_topics()
def test_patch(self): tdata = TOPIC tdata.update({'admin_id', 1}) Topic.create(**tdata) data = {'description': 'Broken bad'} r = self.patch(self._path.format(1), body=data) body = TOPIC body.update(data) body.update({'status': 1, 'id': 1, 'admin': self._me['username']}) self.assertEqual(r.code, 200) self.assertDictEqual(json.loads(r.body), body) self._mox.VerifyAll()
def test_submit(self): """Tests whether posts can be put inside the database.""" self.post = Post( title="Title", text="Text", user_id=1, topics=[Topic(tag_name="topic1"), Topic(tag_name="topic2")]) self.post.upvotes = 1 self.post.downvotes = 0 self.post.importance = 1 self.post.score = self.post.get_score() db.session.add(self.post) db.session.commit()
def test_add_new_comment(self): """Tests whether a new comment can be added.""" self.post = Post( title="Title", text="Text", user_id=1, topics=[Topic(tag_name="topic1"), Topic(tag_name="topic2")], id=1) db.session.add(self.post) db.session.commit() self.comment = Comment(text="This is a test", post_id=self.post.id) db.session.add(self.comment) db.session.commit()
def test_downvoting(self): """Tests whether posts can be downvoted or not.""" self.post = Post( title="Title", text="Text", user_id=1, topics=[Topic(tag_name="topic1"), Topic(tag_name="topic2")], id=1) self.post.downvotes = 1 db.session.add(self.post) db.session.commit() self.post.downvotes += 1 db.session.commit()
def test_can_delete_post(self): """Tests whether a post can be deleted.""" self.post = Post( title="Title", text="Text", user_id=1, topics=[Topic(tag_name="topic1"), Topic(tag_name="topic2")], id=99) db.session.add(self.post) db.session.commit() db.session.delete(self.post) db.session.commit() posts = self.assertIsNone(Post.query.filter_by(id=99).first())
def get_topic(topic): if bool(Topic.query.filter(Topic.name.contains(topic)).first()): return Topic.query.filter(Topic.name.contains(topic)).first() new_topic = Topic(name=topic) db.session.add(new_topic) db.session.commit() return new_topic
def create_topic(): question = request.form['question'] answer = request.form['answer'] newTopic = Topic(question=question, answer=answer) db.session.add(newTopic) db.session.commit() return redirect('/manage')
def test_topic_follows(self): u1 = User.create(email='*****@*****.**', password='******') u2 = User.create(email='*****@*****.**', password='******') topic = Topic.create(title='美术', author=u2) db.session.add_all([u1, u2, topic]) db.session.commit() self.assertFalse(u1.is_following_topic(topic)) self.assertFalse(topic.is_followed_by(u1)) timestamp_before = datetime.datetime.utcnow() u1.follow(topic) timestamp_after = datetime.datetime.utcnow() self.assertTrue(u1.is_following_topic(topic)) self.assertTrue(topic.is_followed_by(u1)) self.assertTrue(u1.followed_topics.count() == 1) self.assertTrue(topic.followers.count() == 1) t = u1.followed_topics.all()[0] self.assertTrue(t.followed == topic) self.assertTrue(timestamp_before <= t.timestamp <= timestamp_after) u1.unfollow(topic) db.session.add(u1) db.session.commit() self.assertFalse(u1.is_following_topic(topic)) self.assertFalse(topic.is_followed_by(u1)) self.assertTrue(u1.followed_topics.count() == 0) self.assertTrue(topic.followers.count() == 0) self.assertTrue(FollowTopic.query.count() == 0)
def create(): form = TopicForm() topic = Topic(name=form.name.data, description=form.description.data) db.session.add(topic) db.session.commit() flash('New Topic Added!') return redirect(url_for('topics.show', id=topic.id)) # redirect to the topic.show view for the newly created topic
def post(self, topic_id): title = self.get_argument('title', None) keywords = self.get_argument('keywords', None) content = self.get_argument('content', '') keep_silent = int(self.get_argument('keep_silent', 0)) is_draft = int(self.get_argument('is_draft', 0)) if not all([title, keywords]): raise exceptions.EmptyFields() else: can_post = yield gen.maybe_future(Topic.can_post(topic_id)) if not can_post: raise exceptions.TopicIsNotAccepted exists = yield gen.maybe_future(Post.get_by_title(title)) if exists: raise exceptions.PostTitleAlreadyExists() else: username = self.current_user yield gen.maybe_future( Post.create(username, topic_id, title, keywords, content, keep_silent=keep_silent, is_draft=is_draft)) # Update gold. update_gold.apply_async(('new_post', username))
def load_sentences(): """Load the content of data.yml into the English / Latin tables""" yaml = open('data/quiz_data.yml') data = ruamel.yaml.load(yaml, ruamel.yaml.RoundTripLoader) print data for topic_name, quiz in data.items(): topic = (Topic.query.filter_by(name=topic_name).first() or Topic(name=topic_name)) print topic topic.save() for quiz_name, sentences in quiz.items(): quiz = Quiz(name=quiz_name, topic=topic) print quiz quiz.save() for question, answers in sentences.items(): type = answers.pop(0)['type'] q = Sentence(type=type, text=question, quiz=quiz) for answer in answers: a = Sentence(text=answer, ) q.translations.append(a) a.translations.append(q) db.session.add(q) db.session.commit()
def get(self, topic_id): topic = yield gen.maybe_future(Topic.get(topic_id)) if not topic: raise HTTPError(404) user = yield gen.maybe_future(User.get(topic.admin_id)) up_votes = yield gen.maybe_future(TopicUpVote.count_by_topic(topic_id)) down_votes = yield gen.maybe_future( TopicDownVote.count_by_topic(topic_id)) up_voted, down_voted = False, False username = self.current_user if username is not None: up_voted = bool((yield gen.maybe_future( TopicUpVote.get_by_user_topic(username, topic_id)))) down_voted = bool((yield gen.maybe_future( TopicDownVote.get_by_user_topic(username, topic_id)))) self.render( 'proposal.html', title=topic.name, keywords=topic.name + ', 2L', description=topic.description, id=topic.id, avatar=topic.avatar, rules=topic.rules, why=topic.why, state=topic.state, date=topic.date, user=user.username, # user_avatar=user.profile.avatar, up_votes=up_votes, down_votes=down_votes, up_voted=int(up_voted), down_voted=int(down_voted), )
def genfake(): config = os.getenv('FLASK_CONFIG') or 'default' if config == 'default' or config == 'development': print("delete all files ...") db.drop_all() db.create_all() print("creating roles ...") Role.insert_roles() print("creating cities ...") City.insert_cities() print("creating topics ...") Topic.insert_topics() print("creating users ...") User.generate_fake() print("creating conferences ...") Conference.generate_fake() print("creating comments ...") Comment.generate_fake()
def add_topic(): form = new_topic_forme() if form.validate_on_submit(): data = form.data topic_s = Topic(topic_s=data["topic"], user_id=session["user_id"]) db.session.add(topic_s) db.session.commit() return redirect("/topic/") return render_template("home/new_topic.html", form=form)
def build_topic_2(): test_topic_2 = Topic( topic_id=2, body='A VR company is seeking computer vision experts', title=u'VR & AR', created_time=datetime.utcnow(), rate=150.0, expert_id=101) return test_topic_2
def test_can_fetch_post(self): """Tests whether posts can be fetched from the database.""" self.post = Post( title="Title", text="Text", user_id=1, topics=[Topic(tag_name="topic1"), Topic(tag_name="topic2")], id=1) self.post.upvotes = 1 self.post.downvotes = 0 self.post.importance = 1 self.post.score = self.post.get_score() db.session.add(self.post) db.session.commit() self.query = Post.query.filter_by(id=1).first() self.query = Post.query.filter_by(user_id=1).first()
def import_topics(from_cache=False): Topic.query.delete() db.session.commit() if from_cache: with open(os.path.dirname(os.path.realpath(__file__)) + '/../' + settings.TOPIC_DATA_CACHE, mode='r') as cachejson: data = json.load(cachejson) for topic in data: db_first_or_create(Topic, commit=False, name=topic['name'], wikipedia_parent=None if topic['wikipedia_parent'] == '' else topic['wikipedia_parent'] ) db.session.commit() if not from_cache: Topic.populate_topics_from_phantom_forms() with open(os.path.dirname(os.path.realpath(__file__)) + '/../' + settings.TOPIC_DATA_CACHE, mode='w') as cachejson: json.dump([json.loads(t.json) for t in Topic.query.all()], cachejson, indent=4)
def build_topic_1(): test_topic_1 = Topic( topic_id=1, body= 'Our company needs a real-time recommendation system, who can help us?', title=u'推荐系统求助', created_time=datetime.utcnow(), rate=100.0, expert_id=101) return test_topic_1
def test_check_topic_exists_func(self): """Tests whether check_topic_exists function work.""" self.test_topic_str = "test" self.test_topic = Topic(tag_name=self.test_topic_str) db.session.add(self.test_topic) db.session.commit() self.assertTrue(check_topic_exists(self.test_topic_str)) self.assertFalse(check_topic_exists("BEFALSE"))
def get(self): users = yield gen.maybe_future(User.count()) topics = yield gen.maybe_future(Topic.count()) posts = yield gen.maybe_future(Post.count()) comments = yield gen.maybe_future(Comment.count()) raise gen.Return({ 'users_count': users, 'topics_count': topics, 'posts_count': posts, 'comments_count': comments, })
def test_filter_comment(self): """Tests whether a comment can be filtered by post_id.""" self.post = Post( title="Title", text="Text", user_id=1, topics=[Topic(tag_name="topic1"), Topic(tag_name="topic2")], id=1) db.session.add(self.post) db.session.commit() self.comment = Comment(text="This is a test", post_id=self.post.id) db.session.add(self.comment) db.session.commit() comments = Comment.query.filter_by(post_id=self.post.id) for i in comments: self.assertEqual(i.text, self.comment.text)
def patch(self, topic_id): fields = dict() for key in ('description', 'rules', 'avatar', 'state'): value = self.get_argument(key, None) if value is not None: fields[key] = value if not fields: raise exceptions.EmptyFields() else: topic = yield gen.maybe_future(Topic.get(topic_id)) yield gen.maybe_future(topic.update(**fields))
def add_topic(): name = request.json['name'] news_id = request.json['news_id'] new_topic = Topic(name, news_id) db.session.add(new_topic) db.session.commit() return jsonify(id=new_topic.id, name=new_topic.name, news_id=new_topic.news_id)
def test_post(self): r = self.post(self._path.format(''), body=TOPIC) data = TOPIC data.update({ 'id': 1, 'admin': self._me['username'], }) self.assertEqual(r.code, 200) self.assertDictEqual(json.loads(r.body), {'status': 1}) topic = Topic.get(1) self.assertDictEqual(topic.to_dict(), data) self._mox.VerifyAll()
def admin_add_topic(): new_data = request.get_json()['newData'] result = Topic.query.filter(Topic.name == new_data['name']).first() if result: return forbidden("已存在,不能重复添加") try: topic = Topic(name=new_data['name'], icon_name=new_data['icon_name']) db.session.add(topic) db.session.commit() return jsonify({'success': True, 'data': True}) except: db.session.rollback() return forbidden('添加失败')
def importDefaultTopic(): topicModel = Topic() path = "file/zhenX.docx" doc = docx.Document(path) paras = doc.paragraphs parastests = [p.text for p in paras if p.text.isspace() is False] for content in parastests: topic_list = content.split("\n") for topic in topic_list: topic = topic.strip() if topic.isspace() is False and topic != '': try: topic_arr = topic.strip().split(".") if topic_arr and len(topic_arr) > 0: topicModel.addNewTopic(topic_arr[1]) pass pass except Exception as err: print err.message print "wrong:" + topic.strip() pass pass
def load_lessons(): """Load the content of products.yml into the Product table""" yaml = open('data/lessons.yml') data = ruamel.yaml.load(yaml, ruamel.yaml.RoundTripLoader) print data for topic_name, text in data.items(): topic = (Topic.query.filter_by(name=topic_name).first() or Topic(name=topic_name)) print topic topic.text = unicode(text) topic.save()
def test_add_remove_question(self): topic = Topic.create(title='摄影') question = Question.create(title='好吗?') questions = [i.question for i in topic.questions.all()] self.assertListEqual(questions, []) self.assertTrue(topic.questions.count() == 0) topic.add_question(question) questions = [i.question for i in topic.questions.all()] self.assertListEqual(questions, [question]) self.assertTrue(topic.questions.count() == 1) topic.remove_question(question) self.assertFalse(topic.is_in_topic(question)) self.assertTrue(topic.questions.count() == 0)
def markedTopicSign(id): res = None try: account = current_user.account res = Topic.update({ Topic.user: account, Topic.is_used: True }).where(Topic.id == id).execute() except Exception: res = None pass finally: return res pass
def createtopic(): form = CreateTopicForm() if form.validate_on_submit(): topic = Topic.query.filter_by(name=form.name.data).first() if topic: flash('There is already a topic with this name') form.name.value = '' return render_template('createtopic.html', form=form) topic = Topic(name=form.name.data, description=form.description.data, owner=current_user) db.session.add(topic) db.session.commit() return render_template('topic.html', topic=topic) return render_template('createtopic.html', form=form)
def get(self, topic_id): username = self.current_user if topic_id: topic = yield gen.maybe_future(Topic.get(topic_id)) info = yield gen.maybe_future(_topic_info(username, topic)) raise gen.Return(info) else: page = int(self.get_argument('page', 1)) per_page = int(self.get_argument('per_page', 20)) pagination = yield gen.maybe_future( Topic.page_list_all(page, per_page)) result = { 'page': page, 'per_page': per_page, 'has_prev': pagination.has_prev, 'has_next': pagination.has_next, 'pages': pagination.pages, 'total': pagination.total, 'topics': [(yield gen.maybe_future(item.to_dict())) for item in pagination.items], } raise gen.Return(result)
def create_topic(): form = CreateTopicForm() if form.validate_on_submit(): topic = Topic.create(title=form.title.data, description=form.description.data) filename = photos.save(form.photo.data) photo_url = photos.url(form.photo.data) cover_url_sm = image_resize(filename, 30) cover_url = image_resize(filename, 400) topic.cover_url = cover_url topic.cover_url_sm = cover_url_sm db.session.add(topic) db.session.commit() return redirect(url_for('.topics')) return render_template('topic/create_topic.html', form=form)
def addTopic(user_id, title, body, group_id, public=True): """ Add a topic to the database and commit the changes. Returns the topic. args: user_id: int title: string body: string group_id: int public: boolean """ ## Initialize topic attributes topic = Topic(user_id=user_id,title=title,body=body,public=public,group_id=group_id) ## add new topic to the database and commit the change db.session.add(topic) db.session.commit() return topic
def get(self): page = int(self.get_argument('page', 1)) per_page = int(self.get_argument('per_page', 20)) pagination = yield gen.maybe_future( Topic.page_list_all(page, per_page)) result = { 'page': page, 'per_page': per_page, 'has_prev': pagination.has_prev, 'has_next': pagination.has_next, 'pages': pagination.pages, 'total': pagination.total, 'topics': [(yield gen.maybe_future(item.to_dict())) for item in pagination.items], } raise gen.Return(result)
def delete(self, id_): if self.category == 'topic': t = yield gen.maybe_future(Topic.get(id_)) if t and t.state in (-1, 1): raise exceptions.TopicVoteTimeHasPassed() username = self.current_user v = yield gen.maybe_future(self._get_by_user_category(username, id_)) if v: yield gen.maybe_future(v.delete()) count = yield gen.maybe_future(self._count_by_category(id_)) # Update gold. update_gold.apply_async( ('cancel_vote', username, id_, self.category, self.vote_type)) raise gen.Return({'count': count}) else: raise exceptions.NoVoteCanBeCancel()
def addsensor(): if request.is_json: req_data = request.get_json() try: emailData = req_data["email"] sensorNameData = req_data["sensorName"] hostnameData = req_data["hostname"] ipData = req_data["ipAddress"] interfaceData = req_data["netInterface"] locationData = req_data["location"] companyData = req_data["company"] except Exception as err: print("[Error] : {}".format(err)) return nice_json( raise_json_code(400, "Variable Error, Please Fill All the Field")) try: sensor = Sensor(hostname=hostnameData, ip_address=ipData, net_interfaces=interfaceData, location=locationData, company=companyData, topic=Topic()) sensor.set_sensor_name(sensorNameData) user = User.objects.get({'_id': emailData}) user.add_sensor(sensor) user.save() except ValidationError as ve: print("[Error] : {}".format(ve.message)) return nice_json(raise_json_code(400, "Paramter Not Valid")) except DuplicateKeyError: print("[Error] : Duplicate email") return nice_json( raise_json_code( 400, "There is already user with that email address.")) return nice_json( raise_json_code_with_data(200, "Add Sensor Success", sensor.to_son().to_dict())) else: return nice_json( raise_json_code(400, "Please send proper request in json"))
def get(self): page = int(self.get_argument('page', 1)) per_page = int(self.get_argument('per_page', 20)) username = self.current_user pagination = yield gen.maybe_future( Topic.page_list_all_accepted(page, per_page)) result = { 'page': page, 'per_page': per_page, 'has_prev': pagination.has_prev, 'has_next': pagination.has_next, 'pages': pagination.pages, 'total': pagination.total, 'topics': [(yield gen.maybe_future(_topic_info(username, item))) for item in pagination.items], } raise gen.Return(result)
def test_follow_topic(self): u = User(email='*****@*****.**', password='******') topic = Topic(name='history') db.session.add(u) db.session.add(topic) db.session.commit() self.assertFalse(u.is_following_topic(topic)) self.assertFalse(u in topic.followers) u.follow_topic(topic) db.session.add(u) db.session.commit() self.assertTrue(u.is_following_topic(topic)) self.assertTrue(u in topic.followers) u.unfollow_topic(topic) db.session.add(u) db.session.commit() self.assertFalse(u.is_following_topic(topic)) self.assertFalse(u in topic.followers)
def submit(): # The below code is ugly and so are you. """View function for the submit site, which contains a standard form. Creates initial variables for mutable variables like upvotes, downvotes and importance, to avoid any TypeErrors.""" form = SubmitForm() if form.validate_on_submit(): # Checks whether the topic exists, so as to not make identical topics. if check_topic_exists(form.topics.data): topic = Topic.query.filter_by(tag_name=form.topics.data).first() post = Post(title=form.title.data, text=form.text.data, user_id=current_user.id, topics=[topic]) elif not check_topic_exists(form.topics.data): post = Post(title=form.title.data, text=form.text.data, user_id=current_user.id, topics=[Topic(tag_name=form.topics.data)]) # Checks to see if post is link or url. if form.link.data == "": post.is_link = False else: post.is_link = True if form.link.data == "" and form.text.data == "": flash("Please input either a link or text, or both.") return redirect(url_for('submit')) post.upvotes = 1 post.link = form.link.data post.downvotes = 0 post.importance = 10 post.hotness = post.get_hotness() post.score = post.get_score() db.session.add(post) db.session.commit() flash('You have now made a post!') return redirect(url_for('index')) return render_template('submit.html', title='Submit', form=form)
def create_resource( *, session: Session = Depends(get_session), resource: ResourceCreate, current_user: User = Depends(deps.get_current_user), ): db_resource = Resource.from_orm(resource, {"user_id": current_user.id}) # get or create the topic topic_ids = [] new_topics = [] for topic in resource.topics: if t := session.exec(select(Topic).where( Topic.name == topic.lower())).one_or_none(): print(t) topic_ids.append(t) else: new = Topic(name=topic.lower()) new_topics.append(new)
def get(self, topic_id): topic = yield gen.maybe_future(Topic.get(topic_id)) if not topic: raise HTTPError(404) admin = yield gen.maybe_future(User.get(topic.admin_id)) is_subscribed = False if self.current_user: is_subscribed = yield gen.maybe_future( Subscription.get_by_user_topic(self.current_user, topic.id)) self.render( 'topic.html', title=topic.name, keywords=topic.name + ', 2L', description=topic.description, topic_id=topic_id, admin=admin.username, avatar=topic.avatar, rules=topic.rules, is_subscribed=int(bool(is_subscribed)), )
def post(self, id_): if self.category == 'topic': t = yield gen.maybe_future(Topic.get(id_)) if t and t.state in (-1, 1): raise exceptions.TopicVoteTimeHasPassed() username = self.current_user v = yield gen.maybe_future(self._get_by_user_category(username, id_)) if v: vote_type = self.vote_type.capitalize() exception = getattr(exceptions, 'CanNotVote{0}Again'.format(vote_type)) raise exception() else: yield gen.maybe_future(self.table.create(username, id_)) count = yield gen.maybe_future(self._count_by_category(id_)) # Update gold. update_gold.apply_async( ('vote', username, id_, self.category, self.vote_type)) raise gen.Return({'count': count})
def check_proposal(topic_id): from app.libs.db import db_session from app.models import Topic, User, TopicUpVote, TopicDownVote from app.settings import Gold user_count = User.count() topic = Topic.get(topic_id) user = User.get(topic.admin_id) up_votes = TopicUpVote.count_by_topic(topic_id) down_votes = TopicDownVote.count_by_topic(topic_id) # Check if the proposal can be accepted or rejected. if (up_votes - down_votes) > (user_count / 2): topic.state = 1 user.profile.gold += Gold['proposal_accepted'] else: topic.state = -1 user.profile.gold += Gold['proposal_rejected'] db_session.add(user) db_session.add(topic) db_session.commit()
def delete(self, topic_id): topic = yield gen.maybe_future(Topic.get(topic_id)) if topic: yield gen.maybe_future(topic.delete())
Cat.insert('Theme') Cat.insert('Jeux') Cat.insert('Technologie') print Cat.get_cat('Yolo') print Cat.get_cat('Jeux') print Cat.get_all_cat() Sous_cat.insert('Couleurs','Theme') Sous_cat.insert('Fleurs','Theme') Sous_cat.insert('Videos','Jeux') Sous_cat.insert('Cartes','Jeux') Sous_cat.insert('Videos','Technologie') Sous_cat.insert('Photos','Technologie') Sous_cat.insert('Robots','Technologie') print Sous_cat.get_sscat('Fleurs','Theme') print Sous_cat.get_all_sscat('Theme') Topic.insert('troc','t','t','t','t') Topic.insert('truc','Sonic','Le herisson, c''est trop bon!','Jeux','Videos') Topic.insert('toto','Mario','Le plombier c''est la nouvelle mode de l''ete','Jeux','Videos') print Topic.get_topic_user('toto') print Topic.get_topic_cat(4) print Topic.get_topic(1) Com.insert(Topic.get_topic_user('toto')[0]['id'],'truc',None,'Les plombiers ils montrent leur raie du cul, c''est degueulasse') Com.insert(Topic.get_topic_user('truc')[0]['id'],'toto',None,'Bwaaah ca va pas ! On mange pas les oursins terrestre !') print Com.get_com_topic(Topic.get_topic_user('truc')[0]['id']) print Com.get_com_user('truc') #from flask import g #if not hasattr(g, 'sqlite_db'): # g.sqlite_db = sqlite3.connect('forum.db') #db = g.sqlite_db