Exemple #1
0
def create_post(member):
    post1 = models.Post("python list",
                        "python list offers a way to structure data",
                        member[1].id)
    sleep(2)  #sleep for 2 second
    post2 = models.Post(
        "writing algorithm",
        "writing alogarithm is very effective when it comes to analyzing problems",
        member[2].id)
    sleep(2)
    post3 = models.Post(
        "classes in python ",
        " classes is a template that has information like variables and functions",
        member[0].id)
    sleep(3)
    post4 = models.Post("hello", "I love Apple", member[2].id)
    sleep(3)
    post5 = models.Post(
        "Engineer ",
        "person trained and skilled in design, construction and use of engineering machines",
        member[0].id)

    print(post1)
    print(post2)
    print(post3)
    print(post4)
    print(post5)
    print("=" * 30)

    return post1, post2, post3, post4, post5
    def post(self):

        Title = self.request.get("post-title")
        Description = self.request.get("post-description")
        Image = self.request.get("post-image")

        gUser = users.get_current_user()
        Author = models.User.get_by_id(gUser.user_id()).key

        if Image:
            post = models.Post(postTitle = Title, postAuthor = Author, postDesc = Description, postImage = Image)
        else:
            post = models.Post(postTitle = Title, postAuthor = Author, postDesc = Description)
        post.put()

        # if Image:
        # post = models.Post(postTitle = Title, postAuthor = Author, postDesc = Description, postImage = Image)
        # else:
        #     post = models.Post(postTitle = Title, postAuthor = Author, postDesc = Description)
        post.put()

        temp_dict = {"postTitle": Title,
                    "postAuthor": Author,
                    "postDesc": Description,
                    "postDate": datetime.now(),
                    "postImage": jinja2.Markup('<img class ="postImage" id = "size" src="/img?img_id=%s"></img>' %
                        post.key.urlsafe())
                }
        temp_dict.update(getAccountHtml())
        template = jinja_env.get_template("templates/confirmPost.html")

        self.response.write(template.render(temp_dict))
def create_posts(members_instances):

    post1 = models.Post("Agriculture", "Agriculture is amazing",
                        members_instances[0].id)
    post2 = models.Post("Engineering", "I love engineering",
                        members_instances[0].id)

    post3 = models.Post("Medicine", "Medicine is great",
                        members_instances[1].id)
    post4 = models.Post("Architecture", "Spectacular art",
                        members_instances[1].id)
    post5 = models.Post("Astronomy", "Space is awesome",
                        members_instances[1].id)

    post6 = models.Post("Geology", "Earth is our friend",
                        members_instances[2].id)
    post7 = models.Post("ComputerSci", "Our passion", members_instances[2].id)
    post8 = models.Post("Algorithms", "Yeah, more of that",
                        members_instances[2].id)
    post9 = models.Post("Operating Systems", "Ewww", members_instances[2].id)

    print(post1)
    print(post2)
    print(post3)
    print("=" * 30)

    return post1, post2, post3, post4, post5, post6, post7, post8, post9
Exemple #4
0
def create_post(members_instance):
    post1 = models.Post("hello", "How are you every body",
                        members_instance[0].id)
    post2 = models.Post("hello", "How are you every body",
                        members_instance[1].id)
    post3 = models.Post("hello", "How are you every body",
                        members_instance[0].id)
    post4 = models.Post("hello", "How are you every body",
                        members_instance[0].id)
    post5 = models.Post("hello", "How are you every body",
                        members_instance[1].id)
    return post1, post2, post3, post4, post5
Exemple #5
0
def add_comment():
    user = utils.session_check(request)
    board = models.Board(request.args.get('board'))
    post = models.Post(id=request.args.get('post'), board=board)
    if 'subject' in request.form:
        subject = request.form['subject'][:int(cfg['max_subject_length'])]
    else:
        subject = ''
    comment = request.form['comment'][:int(cfg['max_comment_length'])]
    if not user or user.fng:
        return utils.response(
            403,
            'You have been banned or have never visited before. If its the latter visit home first.',
            user)
    if not board.name:
        return utils.response(404, 'That board does not exist.', user)
    if not utils.restrict_check(request, board):
        return utils.response(
            403, 'You have been banned from posting in this board.', user)
    post = models.Post(id=request.args.get('post'), board=board)
    if not post.board:
        return utils.response(404, 'That post does not exist.', user)
    if post.thread == 0:
        thread = post.id
    else:
        thread = post.thread
    if 'file' in request.files:
        file = request.files['file']
        if not utils.allowed_file(file):
            return utils.response(
                400, 'The image is of an unacceptable format or too large.',
                user)
        img = models.Image(file=file)
        if not img:
            return utils.response(500, 'Something went wrong. Try again later',
                                  user)
    else:
        img = models.Image(dummy=True)
        img.id = 0
    comment = ">>{}\n{}".format(post.id, comment)
    post = models.Post(board=board,
                       author=user,
                       subject=subject,
                       comment=comment,
                       image=img.id,
                       thread=thread)
    if post:
        return utils.response(201, post.dictate(), user)
    else:
        return utils.response(500, 'Something went wrong. Try again later.',
                              user)
Exemple #6
0
def create_posts():
    post1 = models.Post(
        "First Post",
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
    )
    post2 = models.Post(
        "Second Post",
        "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
    )
    post3 = models.Post(
        "Third Post",
        "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur."
    )

    return post1, post2, post3
Exemple #7
0
def create_posts():
    post1 = models.Post("1st Post", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",1)
    post2 = models.Post("2nd Post", "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", 3)
    post3 = models.Post("3rd Post", "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", 2)
    post4 = models.Post("4th Post", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", 4)
    post5 = models.Post("5th Post", "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", 1)
    post6 = models.Post("6th Post", "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", 3)
    post7 = models.Post("7th Post", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", 1)
    post8 = models.Post("8th Post", "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", 3)
    post9 = models.Post("9th Post", "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", 1)

    return post1, post2, post3, post4, post5, post6, post7, post8, post9
Exemple #8
0
def posts_post():
    """ Add a new post """
    
    # JSON data passed through request
    data = request.json
    
    # Check that the JSON supplied is valid
    # If not you return a 422 Unprocessable Entity
    try:
        validate(data, post_schema)
    except ValidationError as error:
        data = {"message": error.message}
        return Response(json.dumps(data), 422, mimetype="application/json")

    # Add the post to the database
    post = models.Post(title=data["title"], body=data["body"])
    session.add(post)
    session.commit()

    # Return a 201 Created, containing the post as JSON and with the
    # Location header set to the location of the post
    data = json.dumps(post.as_dictionary())
    headers = {"Location": url_for("post_get", id=post.id)}
    return Response(data, 201, headers=headers,
                    mimetype="application/json")
Exemple #9
0
def upload_file(board, post_id=None):
    # Create the post
    post = models.Post(subject=request.form.get('subject'),
                       comment=request.form.get('comment'),
                       parent_id=post_id)
    db_session.add(post)
    db_session.flush()

    # Upload the file if present
    f = request.files['file']

    if f.filename:
        extension = get_extension(f)
        filename = "{0}.{1}".format(post.generate_filename(), extension)
        path = "{0}/static/{1}".format(app.root_path, filename)

        f.save(path)

        post.filename = filename
        post.mimetype = f.mimetype

    db_session.commit()

    # Redirect to page or post
    if post_id:
        return redirect(url_for('reply', board=board, post_id=post_id))
    else:
        return redirect(url_for('page', board=board))
Exemple #10
0
def channel(r):
    chan = models.Channel.query.filter_by(link='@' + r).first()
    if not chan:
        abort(404)
    form = CreatePostForm()
    if form.validate_on_submit():
        if current_user.current_balance < chan.price:
            flash("You do not have enough funds to advertise here")
            return redirect("/channel/" + r)
        post = models.Post(content=form.content.data,
                           link=form.link.data,
                           comment=form.comment.data,
                           channel_id=chan.id,
                           user_id=current_user.id)
        db.session.add(post)
        db.session.commit()

        user = db.session.query(
            models.User).filter_by(email=current_user.email).first()
        user.current_balance -= chan.price
        db.session.commit()

        flash(
            'Great! Your request successfully sent to "%s"\'s administrator!' %
            chan.name)
        return redirect(url_for('marketplace'))
    return render_template('channel.html', chan=chan, form=form)
Exemple #11
0
 def post(self):
     title = request.json['title']
     content = request.json['content']
     newPost = models.Post(title, content)
     db.session.add(newPost)
     db.session.commit()
     return 1
Exemple #12
0
def creat_topic():
	if request.method == "POST":
		new_post = models.Post(request.form["title"], request.form["content"])
		posts_store.add(new_post)
		return redirect(url_for("home"))
	else:
		return render_template("creat_topic.html")
Exemple #13
0
    def setup(self):
        self.user = models.User(id=1, username='******')

        self.post = models.Post(id=1, user_id=1)
        self.post.user = self.user

        self.comment = models.Comment(
            post_id=1,
            user_id=1,
            text='Test text',
            created='2020-01-02',
        )

        self.subcomment = models.SubComment(comment_id=1,
                                            user_id=1,
                                            text='Test text',
                                            created='2020-01-02')
        self.subcomment.user = self.user

        self.comment.user = self.user
        self.comment.post = self.post
        self.comment.subcomments = [self.subcomment]

        self.app = flask_init.app.test_client()
        self.app.testing = True
Exemple #14
0
    def post(self, post_id):
        if post_id == '':  #add new post
            try:
                post = models.Post(**self.__get_settings())
            except Exception as e:
                self.write(str(e))
                return
            self.application.db_session.add(post)
            self.application.db_session.commit()
            #            print(title);
            #            print(contents);
            #            print(contents_html);

            #            post = models.Post(title = title, contents = contents, contents_html = contents_html, author_id = self.current_user.id, time = datetime.datetime.now());
            #            self.application.db_session.add(post);
            #            self.application.db_session.commit();
            self.redirect('/')
        else:  #update old post
            try:
                pid = int(post_id)
                post = self.application.db_session.query(
                    models.Post).filter(models.Post.id == pid).one()
            except:
                self.send_error(404)
                # pid error
                return
            for attr, val in self.__get_settings().items():
                setattr(post, attr, val)
            self.application.db_session.add(post)
            self.application.db_session.commit()
            self.redirect('/')
Exemple #15
0
def add_topic():
    if request.method == 'POST':
        new_post = models.Post(request.form['title'], request.form['content'])
        post_store.add(new_post)
        return redirect(url_for('home'))
    else:
        return render_template("add_topic.html")
Exemple #16
0
def createFakePosts():
    li = LoremIpsum()
    # find out how many users there are
    count = models.User.query.count()

    iterations = 100
    for x in range(iterations):
        # get a random id within the range of the count
        user1Id = random.randint(0, count)

        #create a random string
        li = LoremIpsum()
        li.get_sentences(1+ x%2)


        entry = li.get_sentences(1+ x%2)

        print(entry)
        #entry = falseData.randomStringGenerator(x, x)


        #add it as a post
        #post_text, creator_id, date
        newPost = models.Post(entry, user1Id, datetime.datetime.now())
        db.session.add(newPost)
        db.session.commit()
Exemple #17
0
    def parsequote(self, post):
        """
        Parses and inserts quotes on a post for a specific user.
        The quote is replaced with a placeholder text with the quoted userid attached.
        Later we replace this placeholder text with a random paragraph from that user.
        """
        quoteauthors = post.find_all('div', class_="quotetitle")
        quotecontent = post.find_all('div', class_="quotecontent")

        nr_quotes = len(quotecontent)
        for i in range(nr_quotes):
            authortext = quoteauthors[i].text
            if authortext.endswith("wrote:"):
                authortext = authortext[:-6]
            else:
                authortext = 'GenericQuote'

            if authortext not in self.authorids:
                a = models.User()
                a.username = authortext
                self.db.add(a)
                self.db.flush()
                self.authorids[authortext] = a.id

            quotetext = models.Post()
            quotetext.user_id = self.authorids[authortext]
            content = quotecontent[i].get_text(separator=' ')
            quotetext.content = content
            self.db.add(quotetext)

            ph_text = self.quote_ph + str(self.authorids[authortext])
            quoteauthors[i].replace_with(ph_text)
            quotecontent[i].replace_with('')

        return post.get_text(separator=' ')
Exemple #18
0
async def social_api_post_createPost(request, imgId, imgSrcIndex, title):
    """
    创建一个帖子(需要登陆)
    :param request: 请求
    :param imgId: 图像Id
    :param imgSrcIndex: 图像索引
    :param title: 标题
    :return: 返回帖子对象
    """
    # 获取用户 ID
    username = get_loggined_username_or_denied(request)
    # 创建 Post 对象
    postObj = models.Post(title=title,
                          imageId=imgId,
                          imageSourceIndex=imgSrcIndex,
                          username=username)
    # 保存指定的 ORM 对象
    dbm = request.__dbManager__
    await dbm.insert(postObj)
    # 这里有个问题,如果没任何的评论和点赞信息,那么无法床获得对应的帖子。所以添加一个对应的默认点赞信息和评论信息
    postId = postObj.postId
    defaultliked = models.Like(postId=postId, username='******', liked=True)
    defaultComment = models.Comment(postId=postId,
                                    comment="添加第一条评论吧",
                                    username="******",
                                    to_username=None)
    await dbm.insert(defaultComment)
    await dbm.insert(defaultliked)
    # 返回指定的对象
    return {'postInfo': postObj}
Exemple #19
0
	def _convert(self, gist_id):
		gist = self._fetch(url=('https://api.github.com/gists/' + gist_id))
		# TODO: for now we'll assume there's only 1 file
		markdown = self._has_markdown(gist)
		matches = re.search(r'^---(.*?)---\s*(.*)', markdown['content'], re.DOTALL)
		if matches:
			# our markdown should have a frontmatter block at beginning of file
			meta = yaml.load(matches.groups()[0])

			print(repr(meta))
			# let's assign some fallback values if they're 
			# missing in our frontmatter meta block
			# 
			# fallback to filename of markdown
			title = (meta[self._TITLE_] if self._TITLE_ in meta else markdown['filename']) 
			# fallback to gist created_at date
			created_at = models.normalize_datetime(gist[self._CREATED_AT_]) 
			if self._CREATED_AT_ in meta: 
				# unless created_at was explicitly set in frontmatter
				created_at = datetime.fromordinal(meta[self._CREATED_AT_].toordinal())

			# save our Post meta data
			models.Post(id=gist[self._ID_],
				title=title,
				slug=self._make_slug(created_at, title),
				created_at=created_at,
				updated_at=models.normalize_datetime(gist[self._CREATED_AT_]),
				tags=(meta[self._TAGS_] if self._TAGS_ in meta else []),
				file=markdown['raw_url']
			).put()
Exemple #20
0
Fichier : api.py Projet : jee45/p4
def newPost():

    print("in api: ")
    print(flask.request.form)

    date = datetime.datetime.now()
    creator = flask.session['auth_user']
    entry = flask.request.form['entry']
    url = flask.request.form['url']

    print(" url >>>> api", url)
    # posts should be limited to 256 characters,
    if len(entry) > 255:
        return flask.redirect('/home')

    newPost = models.Post(entry, creator, date)

    if url:
        newPost.url = url

    db.session.add(newPost)
    db.session.commit()

    flask.flash('new post submitted! from api with javascript')
    print(flask.request.form)

    return flask.jsonify({'result': 'ok'})
Exemple #21
0
 def post(create=False):
     if create:
         post = models.Post(title='hello', content='world')
         post.save()
     else:
         post = models.Post.select().get()
     return post
Exemple #22
0
def topic_add():
    if request.method == "GET":
        return render_template("topic_add.html")
    elif request.method == "POST":
        new_post = models.Post(request.form["topictitle"],
                               request.form["topicbody"], 1)
        post_store.add(new_post)
        return redirect(url_for("home"))
 def post(self):
     body = request.get_json()
     post = models.Post(**body).save()
     serialized_data = {
         'id': str(post.id),
         'message': 'Post {0} successfully created.'.format(post.id)
     }
     return Response(json.dumps(serialized_data), mimetype="application/json", status=201)
Exemple #24
0
def create_from_form(form):
	new_post = models.Post()


	form.populate_obj(new_post)

	new_post.put()
	return new_post
Exemple #25
0
 def setUp(self) -> None:
     self.db_name = "test.db"
     with open("requests.json", "r") as file:
         self.requests = json.loads(file.read())
     utils.create_db(self.db_name)
     self.user_model = models.User(self.db_name)
     self.auth_token_model = models.AuthToken(self.db_name)
     self.post_model = models.Post(self.db_name)
Exemple #26
0
def topic_add():
    if request.method == 'POST':
        #sending data to template
        new_post = models.Post(request.form["title"], request.form["content"])
        post_store.add(new_post)
        return redirect(url_for("home"))
    else:
        return render_template("topic_add.html")
Exemple #27
0
def post_new():
    form = forms.PostForm()
    if form.validate_on_submit():
        post = models.Post(form.name.data, form.title.data, form.content.data)
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('post.index'))
    return render_template('post/new.slim', form=form)
Exemple #28
0
def newpost():
    post = models.Post(name=bottle.request.POST.name,
                       text=bottle.request.POST.text)
    try:
        with store.begin(write=True):
            post.save()
    except acid.errors.ConstraintError, e:
        return bottle.redirect('.?error=' + urllib.quote(str(e)))
Exemple #29
0
    def insertposts(self, threadid, page=1):
        """
        Will insert posts from a thread page into the database. It will also insert new authors that it finds.
        Returns True if it's not the last page in the thread.
        """

        # let's start by generating the url from the threadid and page
        start_position = (page - 1) * 10  # post start position for the url
        url = "http://www.awesomenauts.com/forum/viewtopic.php?f=6&t={}&start={}".format(
            threadid, start_position)
        print("Parsing: ", url)

        # now let's fetch the url and create a soup object from it so we can navigate the html code
        r = requests.get(url)
        html = r.text
        soup = BeautifulSoup(html, 'html.parser')

        # helper function we're going to use in the next loop, the postbody html class can contain the post or the signature
        def issignature(post):
            try:
                return post.contents[1] == '_________________'
            except IndexError:
                return False

        posts, authors = [], [
        ]  # will contain posts and users, used to generate the post proper

        # This will loop all posts and signatures, we only care about posts
        for post in soup.find_all('div', class_="postbody"):
            if not issignature(post):
                posts.append(post)

        # Loops authors for each post
        for author in soup.find_all('b', class_="postauthor"):
            authors.append(author.text)

            # insert authors into the db, no duplicates :P
            if author.text not in self.authorids:
                a = models.User()
                a.username = author.text
                self.db.add(a)
                self.db.flush(
                )  # we need to flush to the db to get the id field populated
                self.authorids[author.text] = a.id

        nr_posts = len(posts)
        for i in range(nr_posts):
            post = models.Post()
            post.user_id = self.authorids[authors[i]]
            post.thread_id = threadid
            post.number = (page * 10) + i + 1
            content = self.parsequote(posts[i])
            post.content = content
            self.db.add(post)
        self.db.commit()

        # check if last page
        return soup.find('a', text="Next") is not None
Exemple #30
0
def create_posts(totals_posts):
    posts_list = []
    for i in range(0, totals_posts):
        title = raw_input("Give post's title: \n")
        body = raw_input("Give post's body: \n")
        posts_list.append(models.Post(title, body))
        print(posts_list[-1])
    print("=" * 30)
    return posts_list