Пример #1
0
def edit_post(id):
    today_date = date.today()
    if request.method == "POST":
        title = request.form['title']
        content = request.form['content']
        category_id = request.form['category']

        add_post = Post().update_post([title, content, category_id],
                                      current_user.id)

        return redirect(url_for('dashboard'))
    post = Post().view_single_post(id)

    category = Category().view_all_category()
    return render_template('edit_post.html', post=post, category=category)
Пример #2
0
def seed_db():
    # Seed database with example data

    from models.Post import Post
    from models.User import User
    from main import bcrypt
    from faker import Faker
    import random

    faker = Faker()
    users = []

    for i in range(5):
        user = User()
        user.email = f"test{i}@test.com"
        user.name = faker.name()
        user.password = bcrypt.generate_password_hash("123456").decode("utf-8")
        user.created_at = datetime.now()
        db.session.add(user)
        users.append(user)

    db.session.commit()

    for i in range(20):
        post = Post()
        post.caption = faker.catch_phrase()
        post.created_at = datetime.now()
        post.updated_at = datetime.now()
        post.total_likes = 0
        post.total_comments = 0
        post.user_id = random.choice(users).id
        db.session.add(post)

    db.session.commit()
    print("Tables seeded")
Пример #3
0
def postChallenge():
    data = request.form.to_dict()
    ops = []
    qtype = data['type']
    data['testcases'] = json.loads(data['testcases'])
    lang = langs[data['lang']]
    user = get_jwt_identity()
    if any(bad in data['code'] for bad in lang.invalid):
        ret = ''
        for i in lang.invalid:
            ret += i
        return Response(json.dumps({'success': False, 'err': 'Unsupported functions used.\nCannot use These Functions : '+ret}), mimetype="application/json", status=200)
    else:
        for i, tc in enumerate(data['testcases']):
            op = compile_and_run_code(lang, data['code'], tc)
            if not op['success']:
                if op['timeout']:
                    return Response(json.dumps({'success': False, 'err': 'Time out occured for Case #'+str(i+1)}), mimetype="application/json", status=200)
                else:
                    return Response(json.dumps({'success': False, 'err': 'Error in TestCase #'+str(i+1)+op['err']}), mimetype="application/json", status=200)
            else:
                ops.append(op['output'])

    # return Response(json.dumps({'Success': 'True', 'op': ops}), mimetype="application/json", status=200)
    temp = Post(originalPostBy=user, title=data['title'], qtype=qtype,
                description=data['description'], code=data['code'], testcases=data['testcases'], outputs=ops)
    temp.save()
    User.objects(username=get_jwt_identity()).update_one(push__posts=temp.ID)
    return Response(json.dumps({'success': True, 'link': '/dashboard'}), mimetype="application/json", status=201)
Пример #4
0
def create():
    if request.method == "GET":
        return render_template("create.html")
    else:

        title = str(request.form.get("title"))
        body = request.form.get("body")
        category = request.form.get("category")
        published_at = str(datetime.utcnow())
        user_id = "samjunior101"

        new_post = Post(title=title,
                        body=body,
                        user_id="samjunior101",
                        category=category)

        data = {
            u'title': title,
            u'body': body,
            u'published_at': published_at,
            u'user_id': user_id,
            u'category': category
        }

        Post.save(data=data)

        return redirect(url_for('index'))
Пример #5
0
    def post(self):
        title = self.request.get('title').strip()
        content = self.request.get('content').strip()

        template_vars = {}
        template_vars['errors'] = {}
        template_vars['values'] = {}

        if not title:
            template_vars['errors']['title'] = 'Title is Required'

        if not content:
            template_vars['errors']['content'] = 'Content is Required'

        if len(template_vars['errors']) == 0:
            print 'no errors should create'

            # make post
            post = Post(
                title=title,
                content=content
            )

            # save post
            inserted = post.put()

            # TODO - see if need to handle case where insert fails
            self.redirect('/post/%s' % inserted.id())

        self.render('post_add', template_vars)
Пример #6
0
def category_posts(id):
    posts = Post().view_by_category(id)
    # return json.dumps(post)
    category = Category().view_single_category(id)
    return render_template('category_posts.html',
                           posts=posts,
                           category=category)
Пример #7
0
def run(conf):
    email = conf.facebook_login_email
    password = conf.facebook_login_password
    if email == "" or password == "":
        print(
            "Your email or password is missing. These must both be in conf.py")
        exit()
    reader = PostReader(scrollDepth=conf.depth)
    debug('logging in')
    login(email, password)
    posts = []
    command = conf.command
    if command == "watch-poll":
        if conf.post is None and len(conf.groups) == 0:
            parser.error(
                "--post or --group option must be provided for watch-poll command"
            )
            return
        url = conf.post if not (conf.post is None) else conf.groups[0]
        while (True):
            debug('reading post')
            post_rep = reader.read_post_as(PollPost.PostInFeed, url=url)
            if post_rep.is_poll():
                debug('post contains poll')
                if post_rep.is_open():
                    debug('post poll is open')
                    do_watch_poll(conf, reader, url)
    elif not (conf.post is None):
        posts.append(Post(reader.read_post(conf.post)))
    else:
        if conf.groups:
            for groupId in conf.groups:
                posts.extend(
                    [Post(rep) for rep in reader.read_group_posts(groupId)])
        if conf.pages:
            for pageName in conf.pages:
                posts.extend(
                    [Post(rep) for rep in reader.read_page_posts(pageName)])

    inform_user(encode(posts))
Пример #8
0
    def post(self):
        subject = self.request.get('subject')
        content = self.request.get('content')

        if subject and content:
            p = Post(parent=Utils().blog_key(), author=self.user,
                     subject=subject, content=content)
            p.put()
            return self.redirect('/blog/%s' % str(p.key().id()))
        else:
            error = "subject and content are both needed!"
            self.render("newpost.html", subject=subject,
                        content=content, error=error)
    def new_post(self):
        tittle = input("Enter post Tittle: ")
        content = input("Enter post Content: ")
        date = input("Enter post date, or leave blank for today (in format DDMMYYYY ): ")
        if date == "":
            date = datetime.datetime.utcnow() # put localmachineDate in Date with DateFormat
        else:
           date=datetime.datetime.strptime(date, "%d%m%Y") #parse str to DateFormat

        post = Post(blog_id=self.id,
                    tittle=tittle,
                    content=content,
                    author=self.author,
                    date=date)
        post.save_to_mongo()
Пример #10
0
    def post(self):
        if self.user:
            subject = self.request.get("subject")
            content = self.request.get("content")

            if subject and content:
                new_post = Post(subject=subject,
                                content=content,
                                author=self.user.name)
                new_post.put()
                self.redirect("/post/%s" % str(new_post.key.id()))
            else:
                error = "Both fields are required"
                self.render_page("newpost.html", subject, content, error=error)
        else:
            self.redirect("/login")
Пример #11
0
    def new_post(self):
        title = raw_input("Enter post title: ")
        content = raw_input("Enter post content: ")
        date = raw_input(
            "Enter post date, or leave blank for today (in format DDMMYYYY): ")

        if date == "":
            date = datetime.datetime.utcnow()
        else:
            date = datetime.datetime.strptime(date, "%d%m%Y")

        post = Post(blog_id=self.id,
                    title=title,
                    content=content,
                    author=self.author,
                    date=date)
        post.save_to_mongo()
Пример #12
0
def post_create(user):
    #Create a new post
    post_fields = post_schema.load(request.json)

    new_post = Post()
    new_post.caption = post_fields["caption"]
    new_post.created_at = datetime.now()
    new_post.updated_at = datetime.now()
    new_post.total_comments = 0
    new_post.total_likes = 0
    new_post.total_dislikes = 0

    user.posts.append(new_post)

    db.session.commit()
    
    return jsonify(post_schema.dump(new_post))
Пример #13
0
def post_create():

    post_name = request.form.get("post_name")
    post_description = request.form.get("post_description")
    profile = Profiles.query.filter_by(user_id=current_user.id).first()
    new_post = Post()
    new_post.post_name = post_name
    new_post.post_description = post_description
    new_post.profile_id = current_user.id
    # new_post.profile_id = profile.profileid

    #profile.post.append(new_post)

    db.session.add(new_post)
    db.session.commit()

    # return jsonify(post_schema.dump(new_post))
    return redirect(url_for('post.post_index'))
Пример #14
0
def posts():
    today_date = date.today()
    now_time = datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
    if request.method == "POST":
        author = current_user.id
        title = request.form['title']
        content = request.form['content']
        publish_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        permalink = title.replace(' ', '-').lower() + "-" + now_time
        isPublish = 1
        category_id = request.form['category']
        add_post = Post([
            author, title, content, publish_date, permalink, isPublish,
            category_id
        ]).create_post()

        return redirect(url_for('dashboard'))
    category = Category().view_all_category()
    return render_template("new_post.html", category=category)
Пример #15
0
def seed_db():
    from models.Profiles import Profiles
    from faker import Faker
    from models.Users import Users
    from main import bcrypt
    from models.Post import Post
    import random

    faker = Faker()
    profiles = []
    true_or_false = [True, False]
    posts = []

    for i in range(10):
        user = Users()
        user.email = f"test{i}@test.com"
        user.password = bcrypt.generate_password_hash("123456").decode("utf-8")
        db.session.add(user)
        #accounts.append(user)
    db.session.commit()

    for i in range(10):
        profile = Profiles()
        profile.username = faker.name()
        profile.fname = faker.first_name()
        profile.lname = faker.last_name()
        profile.account_active = faker.boolean()
        profile.user_id = i + 1

        db.session.add(profile)
        profiles.append(profile)
    db.session.commit()

    for i in range(30):
        new_post = Post()
        new_post.post_name = faker.name()
        new_post.post_description = faker.catch_phrase()
        new_post.profile_id = random.choice(profiles).profileid
        posts.append(new_post)
        db.session.add(new_post)
    db.session.commit()

    print("Tables seeded")
def post_create():

    username_of_jwt = get_jwt_identity()

    user_of_jwt = User.query.get(username_of_jwt)

    if not user_of_jwt:
        return abort(404, description="User does not exist")

    # user_id = get_jwt_identity()
    post_object_from_fields = Post()

    post_object_from_fields.username = username_of_jwt
    post_object_from_fields.content = request.json["content"]

    db.session.add(post_object_from_fields)

    db.session.commit()

    return jsonify(post_schema.dump(post_object_from_fields))
Пример #17
0
def post_create(user=None):
    user_id = get_jwt_identity()
    post_fields = post_schema.load(request.json)
    profile = Profiles.query.get(user_id)

    new_post = Post()
    new_post.post_name = post_fields["post_name"]
    new_post.post_description = post_fields["post_description"]
    new_post.account_active = post_fields["account_active"]
    new_post.front_end = post_fields["front_end"]
    new_post.back_end = post_fields["back_end"]
    new_post.full_stack = post_fields["full_stack"]
    new_post.completed = post_fields["completed"]
    new_post.post_github = post_fields["post_github"]

    profile.post.append(new_post)

    db.session.add(new_post)
    db.session.commit()

    return jsonify(post_schema.dump(new_post))
Пример #18
0
    def post(self):
        """
        Attempt to create a new blog post
        """
        current_user = self.authenticate_user()

        if not current_user:
            self.redirect("/login")
        else:
            content = self.request.get("content")
            title = self.request.get("subject")

            if not content or not title:
                self.render_front(title, content, "We need both a title and content")
            else:
                post = Post(title=title, content=content, user=current_user.key)
                post.put()

                current_user.posts.append(post.key)
                current_user.put()

                self.redirect("/post/" + str(post.key.id()))
Пример #19
0
    def post(self):
        if not self.user:
            return self.redirect("/login")

        subject = self.request.get('subject')
        content = self.request.get('content')
        user_id = self.request.cookies.get('user_id').split('|')[0]

        if subject and content:
            p = Post(subject=subject, content=content, user_id=user_id)
            p.put()

            l = LikeCount(blog_id=str(p.key().id()), count=0)
            l.put()

            self.redirect('/blog/%s' % str(p.key().id()))

        else:
            error = "Both subject and content are required!"
            self.render("newpost.html",
                        subject=subject,
                        content=content,
                        error=error)
Пример #20
0
def new_post_form():
    user = current_user
    post_form = NewPostForm()
    if post_form.validate_on_submit():
        # We first create the post, then process the image to give it the correct name
        new_post = Post(user_id=user.id,
                        username=user.username,
                        image_name='',
                        description=post_form.description.data,
                        tags=post_form.tags.data)
        # We add and commit so that the post gets attributed an id in the database
        db.session.add(new_post)
        db.session.commit()
        image = post_form.image.data
        old_filename, file_extension = os.path.splitext(image.filename)
        image.filename = str(new_post.id) + str(file_extension)
        new_post.image_name = image.filename
        images_upload_set.save(image)
        # We commit again to add the new image name to the post
        db.session.commit()
        return redirect(url_for('profile.profile_index'))
    return render_template('post/create_post.html.jinja2',
                           user=user,
                           post_form=post_form)
Пример #21
0
def index():
    posts = Post().view_all_post()
    # return json.dumps(posts)
    return render_template("index.html", posts=posts)
def seed_db():

    from models.User import User
    from models.StudyHistory import StudyHistory
    from models.WorkHistory import WorkHistory
    from models.Certification import Certification
    from models.ResumeProject import ResumeProject
    from models.Meeting import Meeting
    from models.Message import Message
    from models.Connection import Connection
    from models.Post import Post
    from models.JobSalary import JobSalary
    from models.ITNews import ITNews
    from main import bcrypt
    from faker import Faker
    from random import randrange, choice

    from datetime import datetime

    now = datetime.now()

    faker = Faker()

    user_list = []

    # Create fake users

    for i in range(5):
        user = User()
        user.username = f"test{i}"
        user.first_name = faker.first_name()
        user.last_name = faker.last_name()
        user.created_at = now.strftime('%Y-%m-%d %H:%M:%S')
        user.email = f"test{i}@gmail.com"
        user.password = bcrypt.generate_password_hash("123456").decode("utf-8")
        user.mobile = faker.phone_number()
        user.city = faker.city()
        user.country = faker.country()
        user.dob = faker.date_of_birth()

        db.session.add(user)
        user_list.append(user)
    
    

    db.session.commit()

    studyhistory_list = []
    
    qualifications = ['bachelor', 'master', 'honours']
    institutions = ['rmit', 'latrobe', 'monash']
    for i in range(20):

        studyhistory = StudyHistory()
        studyhistory.username = choice(user_list).username

        studyhistory.qualification_title = choice(qualifications)
        studyhistory.institution = choice(institutions)
        studyhistory.city = faker.city()
        studyhistory.country = faker.country()
        studyhistory.date_start = faker.date_of_birth()
        studyhistory.date_end = faker.date_of_birth()

        db.session.add(studyhistory)
        studyhistory_list.append(studyhistory)


    db.session.commit()

    company = ['nab', 'aws', 'microsoft']
    job_title = ['engineer', 'developer', 'architect']
    for i in range(20):

        workhistory = WorkHistory()

        workhistory.username = choice(user_list).username

        workhistory.job_title = faker.job()
        workhistory.company = choice(company)
        workhistory.city = faker.city()
        workhistory.country = faker.country()
        workhistory.date_start = faker.date_of_birth()
        workhistory.date_end = faker.date_of_birth()

        db.session.add(workhistory)


    cert_names = ['aws cloud practitioner', 'microsoft azure administrator', 'microsoft excel']
    descriptions = ['Expert', 'Advanced', 'Beginner']
    issuers = ['Microsoft', 'AWS', 'Google']

    for i in range(20):

        certification = Certification()

        certification.username = choice(user_list).username

        certification.cert_name = choice(cert_names)
        certification.description = choice(descriptions)
        certification.issuer = choice(issuers)
        certification.date_obtained = faker.date_of_birth()

        db.session.add(certification)


    resume_paths_list = ['file1', 'file2', 'file3']
    github_account_list = ['https://github.com/mrixon95', 'https://github.com/HarryTranAU/', 'https://github.com/ashley190']


    for i in range(20):

        resumeproject = ResumeProject()

        resumeproject.username = choice(user_list).username

        resumeproject.resume_path = choice(resume_paths_list)
        resumeproject.github_account = choice(github_account_list)

        db.session.add(resumeproject)


    qualifications = ['bachelor', 'master', 'honours']
    institutions = ['rmit', 'latrobe', 'monash']


    for i in range(20):

        meeting = Meeting()
        meeting.username = choice(user_list).username

        meeting.time_start = faker.date_of_birth()
        meeting.time_end = faker.date_of_birth()
        meeting.location = faker.city()
        meeting.subject = faker.word()
        meeting.description = faker.word()
        meeting.last_updated = faker.date_of_birth()

        db.session.add(meeting)

    db.session.commit()


    for i in range(5):

        message = Message()
        message.username_of_sender = user_list[i].username
        message.username_of_receiver = user_list[(i + 1) % 5].username
        message.content = faker.text()

        db.session.add(message)

    
    for i in range(5):

        connection = Connection()
        connection.username_of_requester = user_list[i % 5].username
        connection.username_of_confirmer = user_list[(i + 3) % 5].username
        connection.user_1_approved = True
        connection.user_2_approved = True
        connection.status = "confirmed"

        db.session.add(connection)



    for i in range(5):

        post = Post()
        post.username = user_list[i % 5].username
        post.content = faker.text()
        post.last_updated = faker.date_of_birth()
        
        db.session.add(post)

    
    for i in range(5):

        jobsalary = JobSalary()
        jobsalary.title = faker.job()
        jobsalary.lower_quartile = faker.random_int(30, 50)
        jobsalary.median_salary = faker.random_int(70, 120)
        jobsalary.upper_quartile = faker.random_int(150, 500)
        jobsalary.average_years_experience = faker.random_int(1, 10)

        db.session.add(jobsalary)

    for i in range(5):

        ITnews = ITNews()
        ITnews.article_link = faker.url()
        ITnews.photo_link = faker.image_url()
        ITnews.published_time = faker.past_date()

        db.session.add(ITnews)



    db.session.commit()
Пример #23
0
def add_post_to_db(t, c, u_id):
    test_post = Post(title=t, content=c, user_id=u_id)
    db.session.add(test_post)
    db.session.commit()
    return test_post.id
Пример #24
0
def seed_db():
    from models.Profiles import Profiles
    from faker import Faker
    from models.Users import Users
    from main import bcrypt
    from models.Post import Post
    from models.Messages import Messages
    import random

    faker = Faker()
    profiles = []
    true_or_false = [True, False]
    posts = []

    for i in range(10):
        user = Users()
        user.email = f"test{i}@test.com"
        user.password = bcrypt.generate_password_hash("123456").decode("utf-8")
        db.session.add(user)
        #accounts.append(user)
    db.session.commit()

    for i in range(10):
        profile = Profiles()
        profile.username = faker.name()
        profile.fname = faker.first_name()
        profile.lname = faker.last_name()
        profile.account_active = faker.boolean()
        profile.user_id = i + 1
        profile.github = faker.name()
        profile.front_end = random.choice(true_or_false)
        profile.back_end = random.choice(true_or_false)
        profile.full_stack = random.choice(true_or_false)
        db.session.add(profile)
        profiles.append(profile)
    db.session.commit()

    for i in range(30):
        new_post = Post()
        new_post.post_name = faker.name()
        new_post.post_description = faker.catch_phrase()
        new_post.account_active = random.choice(true_or_false)
        new_post.front_end = random.choice(true_or_false)
        new_post.back_end = random.choice(true_or_false)
        new_post.full_stack = random.choice(true_or_false)
        new_post.completed = random.choice(true_or_false)
        new_post.post_github = faker.url()
        new_post.profile_id = random.choice(profiles).profileid
        posts.append(new_post)
        db.session.add(new_post)
    db.session.commit()

    for i in range(50):
        new_message = Messages()
        new_message.post_id = random.choice(posts).postid
        new_message.profile_id = random.choice(profiles).profileid
        new_message.messages = faker.catch_phrase()
        new_message.timestamp = faker.date_between(start_date="-1y",
                                                   end_date="+1y")
        db.session.add(new_message)
    db.session.commit()

    print("Tables seeded")
Пример #25
0
with db_session:
    p = Post.get(post_pk=1)
    Comment(content="你瞅啥", post=p)
    Comment(content="瞅你咋地", post=p)

    # 查看关联的数据
    print(p.comments)

# 之后就可以通过p.comments取到与之关联的评论。
# 那么再来试试多对多关系

with db_session:
    c1 = Category(name="tech")
    c2 = Category(name="blog")

    Post(title="第5篇文章", content="Hello world too", categories=[c1])
    Post(title="第6篇文章", content="Hello world 3", categories=[c1, c2])

    # 查看关联的数据
    print(Category["tech"].posts)  # 这个Category["tech"]等同于Category.get("tech")
    print(Post[6].categories)

# 删除
# 调用Entity实例的.delete()方法可以删掉这条数据。
# 如果需要把相关联的数据一并删掉,需要在定义model字段的时候加上cascade_delete = True的参数。

with db_session:
    Category["tech"].delete()

# 查询PonyORM的查询方式比较魔性,和别的ORM有较大区别,这里给个简单的例子看看样子。
# 用Entity对象上的select方法,传入lambda 表达式进行查询,查了id大于2并且内容包含"world"的条目。
Пример #26
0
def show_post(permalink):
    post = Post().view_by_permalink(str(permalink))

    # return json.dumps(post)
    return render_template('single_post.html', post=post)
Пример #27
0
def delete(id):
    update_post = Post().delete_post(id)
    # return id
    return redirect(url_for('dashboard'))
Пример #28
0
def publish(id):
    update_post = Post().publish(id)
    # return id
    return redirect(url_for('dashboard'))
Пример #29
0
def create_post(title, content):
    Post(title=title, content=content)
Пример #30
0
def dashboard():
    posts = Post().view_by_author(current_user.id)
    return render_template("dashboard.html", posts=posts)