Esempio n. 1
0
def seed_jokes():
    
    user1 = User.query.get(1)
    user2 = User.query.get(2)

    joke1 = Joke(
        joke_body='What did the plumber say to the singer?',
        punchline='Nice pipes...',
        rating='G',
        user=user1
    )

    joke2 = Joke(
        joke_body='What do you call a lazy doctor?',
        punchline='Dr Doo-little...',
        rating='G',
        user=user1
    )

    joke3 = Joke(
        joke_body='What do you call a camel in a drought?',
        punchline='A dry humper...',
        rating='PG',
        user=user2
    )

    db.session.add(joke1)
    db.session.add(joke2)
    db.session.add(joke3)
    db.session.commit()
Esempio n. 2
0
def generate_joke():
    if request.method == 'POST':
        r = requests.get('https://geek-jokes.sameerkumar.website/api').text
        dublicate = False
        joke = db.session.query(Joke).filter_by(joke=r, user_id=get_jwt_identity()).first()
        if joke:
            dublicate = True
            return make_response(jsonify({"joke": r, "dublicate": dublicate}), 403)
        joke = Joke(joke=r, user_id=get_jwt_identity())
        db.session.add(joke)
        db.session.commit()
        resp = dict(joke.to_json())
        resp.update({"dublicate": dublicate})
        return make_response(jsonify(resp), 201)
Esempio n. 3
0
class JokeTest(unittest.TestCase):
    def setUp(self):
        '''
        Set up method to run before each test cases.
        '''
        self.new_joke = Joke("Knock knock")

    def test_check_instance_variables(self):
        self.assertEquals(self.new_joke.comments, "Knock Knock")

    def test_save_joke(self):
        """
        To check is jokes are being saved
        """
        self.new_joke.save_joke()
        self.assertTrue(len(Joke.query.all()) > 0)
Esempio n. 4
0
def create_joke():
    """
    Create new joke
    """
    form = CreateJokeForm()
    form["csrf_token"].data = request.cookies["csrf_token"]

    image_error = []
    image = request.files.get("image", None)

    if image is not None:
        image.filename = secure_filename(image.filename)
        pattern = re.compile(".*(apng|avif|jpe?g|png|svg|webp)$",
                             re.IGNORECASE)
        is_image = bool(pattern.match(image.mimetype))
        if not is_image:
            image_error.append(
                "Upload must be an image (apng, avif, jpeg/jpg, png, svg, webp)."
            )

    if form.validate_on_submit() and not image_error:

        output_link = (
            upload_file_to_s3(image) if image else
            "https://pair-yo-pet-aws.s3-us-west-1.amazonaws.com/default-dog.png"
        )

        new_joke = Joke(
            userId=form.data["userId"],
            joke=form.data["joke"],
            imageURL=output_link,
            jokeType=form.data["jokeType"],
        )
        db.session.add(new_joke)
        db.session.commit()
        return new_joke.to_dict()

    errors = validation_errors_to_error_messages(form.errors)
    errors += image_error

    return {"errors": errors}
Esempio n. 5
0
def write_to_db(db):
    # Data cannot be passed as a param because it will be prefetched
    # by the thread and reused.
    try:
        data = fetch_joke(url)
        if Joke.query.filter_by(setup=data['setup']).first() is None:
            joke = Joke(_type=data['type'],
                        setup=data['setup'],
                        punchline=data['punchline'])
            db.session.add(joke)
            db.session.commit()
    except Exception as e:
        print(f"There was an Error: {e}")
Esempio n. 6
0
def add_jokes():
    try:
        f = open("app/data/coldjoke")
        current = 0
        max_line = Joke.query.filter_by().count()
        print(max_line)
        for line in f:
            current = current + 1
            if current <= max_line:
                continue
            print(current)
            joke = Joke(id=current, content=line)
            db.session.add(joke)
    except:
        pass

    db.session.commit()
Esempio n. 7
0
    def add_joke(self, joke_body, author):
        """
        Add new joke to database

        Arguments:
            joke_body: str
            author: User

        Returns:
            None

        Raises:
            InvalidCharacters
            TooShort
            TooLong
        """
        if len(joke_body) < self.JOKE_LENGTH_MIN:
            raise TooShort

        if self.JOKE_LENGTH_MAX < len(joke_body):
            raise TooLong

        # Calculate id by adding one to last joke's id
        all_jokes = self.session.query(Joke).order_by(Joke.id).all()
        try:
            last_joke = all_jokes[-1]
            last_joke_id = last_joke.get_id()
            joke_id = last_joke_id + 1
        except IndexError:  # no jokes in database
            joke_id = 0

        new_joke = Joke(id=joke_id,
                        body=joke_body,
                        vote_count=0,
                        author=author)
        self.session.add(new_joke)
        self.session.commit()
        return
Esempio n. 8
0
def insert_jokes_categories():
    """insert some categories and jokes to test.db"""
    db_testing_categories = [
        Category(name="first category", average_rank=1),
        Category(name="second category", average_rank=2),
        Category(name="third category", average_rank=3),
        Category(name="forth category", average_rank=3.5),
        Category(name="fifth category", average_rank=2.55)
    ]
    db_testing_jokes = [
        Joke(joke="lorem ipsum", joke_length=11, rank=2, category_id=1),
        Joke(joke="lorem ipsum fhjf", joke_length=11, rank=2.5, category_id=1),
        Joke(joke="lorem ipsumdddd aa",
             joke_length=11,
             rank=3.4,
             category_id=4),
        Joke(joke="lorem ipsumawhadj ", joke_length=11, rank=4, category_id=2),
        Joke(joke="lorem ipsum adds", joke_length=11, rank=4, category_id=4),
        Joke(joke="lorem ipsum qwer", joke_length=11, rank=2.55, category_id=2)
    ]
    DB.session.add_all(db_testing_categories)
    DB.session.add_all(db_testing_jokes)
    DB.session.commit()
Esempio n. 9
0
def seed_jokes():

    jokes = [
        Joke(
            userId=1,
            joke="I ate a clock yesterday, it was very time-consuming.",
            imageURL=
            "https://assets-global.website-files.com/5dcc7f8c449e597ed83356b8/5dcc8a5e5473766654e080bb_5d93d0a059ce656959dab196_logo-full-black-2000-p-500.png",
            jokeType="Misc",
        ),
        Joke(
            userId=2,
            joke=
            'Why do we tell actors to “break a leg?” Because every play has a cast.',
            jokeType="Any",
        ),
        Joke(
            userId=3,
            joke=
            'Helvetica and Times New Roman walk into a bar. “Get out of here!” shouts the bartender. “We don’t serve your type.”',
            jokeType="Any",
        ),
        Joke(
            userId=4,
            joke=
            "A perfectionist walked into a bar...apparently, the bar wasn’t set high enough.",
            jokeType="Christmas",
        ),
        Joke(
            userId=2,
            joke="Why was 6 afraid of 7? Because 7 ate 9!",
            jokeType="Pun",
        ),
        Joke(
            userId=5,
            joke=
            "I'm reading an antigravity book apparently, It's impossible to put down!",
            jokeType="Programming",
        ),
        Joke(
            userId=6,
            joke="What kind of cheese doesn't belong to you? Nacho cheese!",
            jokeType="Any",
        ),
        Joke(
            userId=7,
            joke="You can't trust atoms. They make up everything!             ",
            jokeType="Any",
        ),
        Joke(
            userId=8,
            joke="Why did the dog cross the road? To get to the barking lot!",
            jokeType="Any",
        ),
        Joke(
            userId=9,
            joke="AWhy do potatoes argue? Because they can't see eye to eye!",
            jokeType="Any",
        ),
        Joke(
            userId=1,
            joke=
            "Why do mushrooms get invited to all the best parties? Because they are such fungis!",
            jokeType="Any",
        ),
        Joke(
            userId=3,
            joke="Can February March? No, but April May!",
            jokeType="Any",
        ),
        Joke(
            userId=6,
            joke="What's the loneliest cheese? ProvAlone!",
            jokeType="Any",
        ),
        Joke(
            userId=7,
            joke="What kind of dog does Dracula have? A bloodhound!",
            jokeType="Any",
        ),
        Joke(
            userId=8,
            joke="Did you get a haircut? No, I got them all cut!",
            jokeType="Any",
        ),
        Joke(
            userId=9,
            joke="What do you call a cold dog? A chili dog!",
            jokeType="Any",
        ),
        Joke(
            userId=4,
            joke=
            "Why did the cat run away from the tree? It was afraid of the bark!",
            jokeType="Any",
        ),
        Joke(
            userId=2,
            joke="Why don't cannibals eat clowns? Because they taste funny!",
            jokeType="Any",
        ),
        Joke(
            userId=2,
            joke="How do you fix a broken tomato? Tomato paste!",
            jokeType="Any",
        ),
        Joke(
            userId=2,
            joke=
            "Why don't eggs tell each other jokes? They'd crack each other up!",
            jokeType="Any",
        ),
        Joke(
            userId=2,
            joke=
            "Why did the hipster burn his tongue on coffee? Because he drank it before it was cool!",
            jokeType="Any",
        ),
        Joke(
            userId=2,
            joke=
            "Why did the farmer win an award? He was out standing in his field!",
            jokeType="Any",
        ),
    ]

    db.session.bulk_save_objects(jokes)
    db.session.commit()
Esempio n. 10
0
from dotenv import load_dotenv
load_dotenv()

from app import app
from app.models import db, Joke, User

with app.app_context():
    db.drop_all()
    db.create_all()

    user = User(username="******", email="*****@*****.**", password="******")

    joke1 = Joke(joke_body='What did the plumber say to the singer?',
                 punchline='Nice pipes...',
                 rating='G',
                 user=user)

    joke2 = Joke(joke_body='What do you call a lazy doctor?',
                 punchline='Dr Doo-little...',
                 rating='G',
                 user=user)

    joke3 = Joke(joke_body='What do you call a camel in a drought?',
                 punchline='A dry humper...',
                 rating='PG',
                 user=user)

    db.session.add(user)
    db.session.add(joke1)
    db.session.add(joke2)
    db.session.add(joke3)
Esempio n. 11
0
def seed_jokes():

    user1 = User.query.get(1)
    user2 = User.query.get(2)
    user3 = User.query.get(2)

    joke1 = Joke(joke_body='What did the plumber say to the singer?',
                 punchline='Nice pipes...',
                 rating='G',
                 user=user1)
    joke2 = Joke(joke_body='What do you call a lazy doctor?',
                 punchline='Dr Doo-little...',
                 rating='G',
                 user=user1)
    joke3 = Joke(joke_body='What do you call a camel in a drought?',
                 punchline='A dry humper...',
                 rating='PG',
                 user=user1)
    joke4 = Joke(joke_body='Why did the scarecrow win an award?',
                 punchline='Because he was outstanding in his field...',
                 rating='G',
                 user=user2)
    joke5 = Joke(joke_body='What do you call a bundle of hay in a church?',
                 punchline='Christian Bale...',
                 rating='G',
                 user=user2)
    joke6 = Joke(joke_body='Why was the coach yelling at a vending machine?',
                 punchline='He wanted his quarter back...',
                 rating='G',
                 user=user3)
    joke7 = Joke(joke_body='What kind of exercises do lazy people do?',
                 punchline='Diddly squats...',
                 rating='G',
                 user=user3)
    joke8 = Joke(joke_body='How do trees access the internet?',
                 punchline='They log in...',
                 rating='G',
                 user=user1)
    joke9 = Joke(joke_body='How do you weigh a millennial?',
                 punchline='In Instagrams...',
                 rating='G',
                 user=user1)
    joke10 = Joke(
        joke_body='How did Darth Vader know what Luke got him for Christmas?',
        punchline='He felt his presents...',
        rating='G',
        user=user1)
    joke11 = Joke(joke_body='What was Forrest Gump’s email password?',
                  punchline='1forrest1...',
                  rating='PG',
                  user=user2)
    joke12 = Joke(joke_body='What did one ocean say to the other ocean?',
                  punchline='Nothing, they just waved...',
                  rating='G',
                  user=user1)
    joke13 = Joke(joke_body='Why can’t you trust atoms?',
                  punchline='They make up everything...',
                  rating='G',
                  user=user1)
    joke14 = Joke(joke_body='Why did the coffee file a police report?',
                  punchline='It got mugged...',
                  rating='PG',
                  user=user1)
    joke15 = Joke(
        joke_body='What’s an astronaut’s favorite part of the computer?',
        punchline='The space bar...',
        rating='G',
        user=user2)
    joke16 = Joke(joke_body='How do astronomers organize a party?',
                  punchline='They planet...',
                  rating='G',
                  user=user2)
    joke17 = Joke(joke_body='I wrote a song about a tortilla...',
                  punchline='Well actually, it’s more of a wrap...',
                  rating='PG',
                  user=user3)
    joke18 = Joke(joke_body='Why don’t oysters share their pearls?',
                  punchline='Because they’re shellfish...',
                  rating='G',
                  user=user3)

    jokes = [
        joke1, joke2, joke3, joke4, joke5, joke6, joke7, joke8, joke9, joke10,
        joke11, joke12, joke13, joke14, joke15, joke16, joke17, joke18
    ]
    db.session.add_all(jokes)
    db.session.commit()
Esempio n. 12
0
 def setUp(self):
     '''
     Set up method to run before each test cases.
     '''
     self.new_joke = Joke("Knock knock")
Esempio n. 13
0
def get_jokes_list():
    if request.method == 'GET':
        jokes_list = Joke.query.filter_by(user_id=get_jwt_identity()).all()
        return make_response(jsonify(Joke.to_json_list(jokes_list)))