コード例 #1
0
def test_example_data():

    with open('test_melon_news.json') as f:
        melon_news_data = json.loads(f.read())

    melon_news_in_db = []
    for melon_news in melon_news_data:
        comment = melon_news['comment']
        news = melon_news['news']
        user = melon_news['user']
        category = melon_news['category']

        db_melon_news = crud.create_melon_news(comment, news, user, category)

    model.Comment.query.delete()
    model.News.query.delete()
    model.User.query.delete()
    model.Category.query.delete()

    users_in_db = {}
    categories_in_db = {}
    news_in_db = {}

    for user in melon_news_data['users']:
        db_user = crud.create_user(user_name=user['user_name'],
                                   email=user['email'],
                                   user_role=user['user_role'],
                                   password=user['password'])
        users_in_db[db_user.email] = db_user

    for category in melon_news_data['categories']:
        db_category = crud.create_category(
            category_type=category['category_type'],
            description=category['description'])
        categories_in_db[db_category.category_type] = db_category

    for news in melon_news_data['news']:
        db_news = crud.create_news(
            user=users_in_db[news['email']],
            category=categories_in_db[news['category_type']],
            title=news['title'],
            summary=news['summary'],
            article_text=news['article_text'],
            external_link=news['external_link'],
            picture_link=news['picture_link'],
            date_post=DateTime(news['date_post'][0], news['date_post'][1],
                               news['date_post'][2]))
        news_in_db[db_news.title] = db_news

    for comment in melon_news_data['comments']:
        crud.create_comment(user=users_in_db[comment['email']],
                            news=news_in_db[comment['title']],
                            comment_text=comment['comment_text'])

    return melon_news_in_db
コード例 #2
0
def example_data():

    f = open('seeddata.json', )

    data = json.load(f)

    f.close()

    f2 = open('direct-link.json', )

    direct_link_data = json.load(f2)

    f2.close()

    users_in_db = {}
    categories_in_db = {}
    news_in_db = {}

    for user in data['users']:
        db_user = crud.create_user(user_name=user['user_name'],
                                   email=user['email'],
                                   user_role=user['user_role'],
                                   password=user['password'])
        users_in_db[db_user.email] = db_user

    for category in data['categories']:
        db_category = crud.create_category(
            category_type=category['category_type'],
            description=category['description'])
        categories_in_db[db_category.category_type] = db_category

    for news in data['news']:
        db_news = crud.create_news(
            user=users_in_db[news['email']],
            category=categories_in_db[news['category_type']],
            title=news['title'],
            summary=news['summary'],
            article_text=news['article_text'],
            external_link=news['external_link'],
            picture_link=news['picture_link'],
            date_post=datetime(news['date_post'][0], news['date_post'][1],
                               news['date_post'][2]))
        news_in_db[db_news.title] = db_news

    for comment in data['comments']:
        crud.create_comment(user=users_in_db[comment['email']],
                            news=news_in_db[comment['title']],
                            comment_text=comment['comment_text'])

    for direct_link_item in direct_link_data:
        crud.create_external_news(
            direct_title=direct_link_item['direct_title'],
            direct_link=direct_link_item['direct_link'],
            image=direct_link_item['image'])
コード例 #3
0
def example_data():

    os.system('dropdb testmelonnews')
    os.system('createdb testmelonnews')

    model.connect_to_db(server.app)
    model.db.create_all()

    f = open('seeddata.json', )

    data = json.load(f)

    f.close()

    model.Comment.query.delete()
    model.News.query.delete()
    model.User.query.delete()
    model.Category.query.delete()

    users_in_db = {}
    categories_in_db = {}
    news_in_db = {}

    for user in data['users']:
        db_user = crud.create_user(user_name=user['user_name'],
                                   email=user['email'],
                                   user_role=user['user_role'],
                                   password=user['password'])
        users_in_db[db_user.email] = db_user

    for category in data['categories']:
        db_category = crud.create_category(
            category_type=category['category_type'],
            description=category['description'])
        categories_in_db[db_category.category_type] = db_category

    for news in data['news']:
        db_news = crud.create_news(
            user=users_in_db[news['email']],
            category=categories_in_db[news['category_type']],
            title=news['title'],
            summary=news['summary'],
            article_text=news['article_text'],
            external_link=news['external_link'],
            picture_link=news['picture_link'],
            date_post=datetime(news['date_post'][0], news['date_post'][1],
                               news['date_post'][2]))
        news_in_db[db_news.title] = db_news

    for comment in data['comments']:
        crud.create_comment(user=users_in_db[comment['email']],
                            news=news_in_db[comment['title']],
                            comment_text=comment['comment_text'])
コード例 #4
0
def test_db_inset_and_get_comment(session):
    session = session
    fixture = {
        'id': 1,
        'contents': 'hello',
        'writer': '*****@*****.**',
        'article_id': 1
    }
    comment = models.Comment(**fixture)
    crud.create_comment(session, comment)
    comment = crud.get_comment(db=session, comment_id=1)
    assert comment.id == fixture['id'] and comment.contents == fixture['contents'] and \
           comment.writer == fixture['writer']
コード例 #5
0
def submit_comment(location_id):
    """Get comment from user."""

    user_id = session['Current User']
    print('USER ID: ', session['Current User'])
    print("USER ID TYPE: ", type(user_id))
    comment = request.form.get('comment')
    print("LOCATION ID: ", location_id)
    name = crud.get_user_by_id(user_id).name
    print(name)
    crud.create_comment(user_id, name, location_id, comment)

    flash('Comment submitted.')
    return redirect(f'/recycler/{location_id}')
コード例 #6
0
ファイル: server.py プロジェクト: kellibudd/HackTrack
def add_comment():
    """Add a comment."""

    strava_activity_id = request.form.get("activity-id")
    comment = request.form.get("comment")
    activity = crud.get_activity_by_strava_id(strava_activity_id)

    crud.create_comment(
        activity.id,
        session["user_id"],
        activity.user_id,
        datetime.utcnow(),
        comment,
    )

    return redirect(request.referrer)
コード例 #7
0
def post_comment(meetup_id):
    """Post a comment to a meetup."""
    text = request.json['text']

    writer = crud.get_user_by_id(session['user_id'])
    meetup = crud.get_meetup_by_id(meetup_id)
    comment = crud.create_comment(writer, meetup, text)
    return jsonify({'status': 'success', 'comment': comment.to_dict()})
コード例 #8
0
def new_comment():
    is_ajax = request.form.get("ajax",
                               type=int)  # MultiDict(TypeConversionDict)

    form = NewCommentForm()

    if form.validate_on_submit():
        crud.create_comment(item_id=form.item_id.data,
                            content=escape(form.content.data))

        if is_ajax:
            return render_template("_comment.html", content=form.content.data)

    if is_ajax:
        return "Content is required.", 400

    return redirect(url_for("item_detail", item_id=form.item_id.data))
コード例 #9
0
ファイル: community.py プロジェクト: br-kim/japanese_quiz
async def write_comment(request: Request, comment: Comment, db=Depends(get_db)):
    writer = request.session.get('user_email')
    if not (writer and comment.dict().get('contents')):
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
    db_comment = schemas.CommentCreate(writer=writer, contents=comment.contents, article_id=comment.article_id,
                                       parent_id=comment.parent_id)
    created_comment = crud.create_comment(db, db_comment)
    return created_comment.id
コード例 #10
0
def add_comment():
    """User adding a comment to a blog"""

    user_id = session.get("user_id")
    blog_id = request.form.get("blog_id")
    comment = request.form.get("comment")

    blog = crud.get_blog_by_id(blog_id)

    add_comment = crud.create_comment(comment=comment,
                                      user_id=user_id,
                                      blog_id=blog_id)

    flash("Your Comment has been added")

    return redirect('/all_blogs')
コード例 #11
0
def add_comment(activity_id):

    activity = crud.get_activity_by_id(activity_id)
    user = crud.get_user_by_id(session['id'])

    if request.method == 'GET':
        return render_template('activity.html', activity=activity)

    if request.method == 'POST':
        comment_text = request.form['comment']
        star_rating = request.form['rating']

        add_comment = crud.create_comment(comment_text, star_rating)

        db.session.add(add_comment)

        user.comments.append(add_comment)
        activity.comments.append(add_comment)
        db.session.commit()

        flash("Comment added")
        return redirect(url_for('show_activity', activity_id=activity_id))
コード例 #12
0
def update_book_info(book_id):
    """ A function that display info on a book and any comments that have been written about that book """

    if session['user']:
        current_user = crud.get_user_by_username(session['user'])
        book = crud.get_book_by_id(book_id)

        new_comment = request.get_json()
        make_comment = crud.create_comment(current_user.user_id, book_id,
                                           new_comment['comment_text'])

        comments = crud.get_comments_by_book_id(book_id)
        # print(comments, book, "COMMENTS")

        comment_list = []
        for comment in comments:
            # print(comment.comment_text)
            comment_list.append({
                "text": comment.comment_text,
                "user": comment.user.user_name,
                "likes": comment.like_count,
                "post_date": comment.date_written
            })

        image_url = 'https' + str(book.cover_img_source)[4:]
        serialized_book = {
            'book_id': book.book_id,
            "title": book.title,
            'author': book.author,
            'publisher': book.publisher,
            'description': book.description,
            "img": image_url,
            "comments": comment_list
        }

    return jsonify(serialized_book)
コード例 #13
0
for time in time_periods:
    time_period_name = (time['time_period_name'])

    db_time_period = crud.create_time_period(time_period_name)
    time_periods_in_db.append(db_time_period)

with open('data/comments.json') as k:
    comments = json.loads(k.read())

comments_in_db=[]

for comment in comments:
    comment_text, star_rating =(comment['comment_text'], comment['star_rating'])

    db_comment=crud.create_comment(comment_text, star_rating)
    comments_in_db.append(db_comment)



db.session.commit()

sarah = db.session.query(User).filter_by(first_name='Sarah').first()
tegan = db.session.query(Child).filter_by(child_name='Tegan').first()
finley = db.session.query(Child).filter_by(child_name='Finley').first()

sarah.children.append(tegan)
sarah.children.append(finley)

niki = db.session.query(User).filter_by(first_name='Niki').first()
noelle = db.session.query(Child).filter_by(child_name='Noelle').first()
コード例 #14
0
tweet_in_db = []

for tweet in tweet_data:
    handle, post_or_reply, url, content, comments, views, hearts, last_updated = (
        tweet['handle'], tweet['post_or_reply'], tweet['url'],
        tweet['content'], tweet['comments'], tweet['views'], tweet['hearts'],
        tweet['last_updated'])

    db_tweet = crud.create_tweet(handle, post_or_reply, url, content, comments,
                                 views, hearts, last_updated)

    tweet_in_db.append(db_tweet)

# Create comments table's initial data.

with open('data/comment.json') as f:

    comment_data = json.loads(f.read())

comment_in_db = []

for comment in comment_data:
    commentator, comment_summary, replied_to, last_updated = (
        comment['commentator'], comment['comment_summary'],
        comment['replied_to'], comment['last_updated'])

    db_comment = crud.create_comment(commentator, comment_summary, replied_to,
                                     last_updated)

    comment_in_db.append(db_comment)
コード例 #15
0
    mileage, public_trans_date, carbon_footprint, user_id = transit
    transit_travel = crud.create_public_trans(mileage, public_trans_date,
                                              carbon_footprint, user_id)

household_file = open_pipe_file("seed_text_files/household.seed")
for house in household_file:
    num_occupants, income, zipcode, user_id = house
    household = crud.create_household(num_occupants, income, zipcode, user_id)

nat_gas_file = open_pipe_file("seed_text_files/nat_gas.seed")
for nat_gas in nat_gas_file:
    nat_gas_bill, nat_gas_date, carbon_footprint, user_id, household_id = nat_gas
    nat_gas_all = crud.create_monthly_nat_gas(nat_gas_bill, nat_gas_date,
                                              carbon_footprint, user_id,
                                              household_id)

monthly_elect_file = open_pipe_file("seed_text_files/electricity.seed")
for elect in monthly_elect_file:
    elect_bill, elect_date, carbon_footprint, user_id, household_id = elect
    monthly_elect = crud.create_monthly_elect_bill(elect_bill, elect_date,
                                                   carbon_footprint, user_id,
                                                   household_id)

comment_file = open_pipe_file("seed_text_files/comments.seed")
for comment in comment_file:
    text, user_id = comment
    comment_all = crud.create_comment(text, user_id)

# if __name__ == '__main__':
#     from server import app
#     connect_to_db(app)
コード例 #16
0
def create_comment(comment: schemas.CommentCreate, db: Session = Depends(get_db)):
    return crud.create_comment(db=db, comment=comment)
コード例 #17
0
import server

os.system('dropdb youtube_comments')

os.system('createdb youtube_comments')

model.connect_to_db(server.app)

model.db.create_all()

# Create comment table's initial data.

with open('data/comment.json') as f:

    comment_data = json.loads(f.read())

comment_in_db = []

for comment in comment_data:
    columnNamesSeparatedbyCommasUntilLastOne = (comment['channel_name'],
                                                comment['video_number'],
                                                comment['commentator'],
                                                comment['commentary'],
                                                comment['date'],
                                                comment['replied_to'])

    db_comment = crud.create_comment(channel_name, video - number, commentator,
                                     commentary, date, replied_to)

    comment_in_db.append(db_comment)
コード例 #18
0
    new_bookshelf = crud.create_user_bookshelf(
        user_id=n_user.user_id, nickname=f"Shelf_{n_user.user_name}")
    print(f"added new bookshelf to database : {new_bookshelf}")

    for num in range(10):
        make_shelf_books = choice(book_data_seeding)
        reading_stat = choice(reading_data_seeding)
        owned_stat = choice(owned_data_seeding)
        new_shelved_book = crud.create_shelvedbook(
            new_bookshelf.shelf_id, make_shelf_books.book_id,
            reading_stat.reading_status_id, owned_stat.owned_id)

        print(f"added new book to shelf : {new_shelved_book}")
        print(f"books on shelf{new_bookshelf.books}")

for book in book_data_seeding:
    n_user = choice(user_data_seeding)
    print(n_user, book)
    comment = choice([
        'Life-changing. I absolutely recommend reading this book',
        "Boring. Couldn't get into it",
        "I really wanted to like it, but the plot was kind of stale and the narrator's voice irked me. ",
        " i love this book. the characters, the settings, so vivid and detailed. so much energy. great great read.",
        "really well written. you can't do better in the english language for show of mastery of prose.",
        "spoiler: the character's unbridled enthuasism led to the character's downfall."
    ])
    new_comment = crud.create_comment(user_id=n_user.user_id,
                                      book_id=book.book_id,
                                      comment_text=comment)
    print(f"added new comment to database : {new_comment}")