Creating a Hilarious Python Website: A Beginner’s Guide to Memes with Flask

Posted by


In this tutorial, we will walk you through the process of building a meme website using Python and Flask. Flask is a lightweight web framework for Python that makes it easy to build web applications quickly and efficiently. By the end of this tutorial, you will have a basic meme website that users can visit to view and share memes.

Step 1: Setting up your environment
Before we can start building our meme website, we need to set up our development environment. Start by installing Python and Flask on your machine. You can install Python from the official Python website, and Flask can be installed using the pip package manager. Run the following command in your terminal to install Flask:

pip install Flask

Once you have Flask installed, you’re ready to start building your meme website.

Step 2: Creating the Flask app
Create a new directory for your project and navigate to it in your terminal. Inside this directory, create a new Python file called app.py. This will be the main file for your Flask application. In app.py, import the necessary modules:

from flask import Flask

Next, create an instance of the Flask class:

app = Flask(__name__)

This will create a new Flask application that we can use to build our meme website.

Step 3: Setting up routes
Routes are URL patterns that the Flask application can respond to. We will create routes for the home page and the meme page. Define the routes in app.py:

@app.route('/')
def home():
    return 'Welcome to the meme website!'

@app.route('/memes')
def memes():
    return 'Here are the latest memes!'

These routes will display a welcome message on the home page and a list of memes on the meme page.

Step 4: Running the Flask app
To run the Flask app, add the following code to the bottom of app.py:

if __name__ == '__main__':
    app.run(debug=True)

This code will start the Flask development server and run the app in debug mode.

Step 5: Testing the app
To test the app, open your terminal and navigate to the directory where app.py is located. Run the following command:

python app.py

This will start the Flask development server. Open a web browser and navigate to http://127.0.0.1:5000/ to view the home page of your meme website. You can also visit http://127.0.0.1:5000/memes to view the meme page.

Step 6: Adding meme data
Now that we have the basic structure of our meme website set up, let’s add some meme data. Create a new file called memes.py and add a list of meme objects:

memes = [
    {
        'id': 1,
        'image': 'meme1.png',
        'caption': 'Funny meme 1'
    },
    {
        'id': 2,
        'image': 'meme2.png',
        'caption': 'Funny meme 2'
    },
    {
        'id': 3,
        'image': 'meme3.png',
        'caption': 'Funny meme 3'
    }
]

This data represents the memes that will be displayed on the meme page. You can add as many meme objects as you want.

Step 7: Displaying memes on the meme page
Update the memes route in app.py to display the memes from the memes.py file:

from memes import memes

@app.route('/memes')
def memes():
    return render_template('memes.html', memes=memes)

This code will pass the memes list to the memes.html template, where we will display the memes.

Step 8: Creating the memes template
Create a new directory in your project called templates. Inside this directory, create a new HTML file called memes.html with the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Meme Website</title>
</head>
<body>
    <h1>Latest Memes</h1>
    <ul>
        {% for meme in memes %}
            <li>
                <img src="{{ url_for('static', filename=meme['image']) }}" alt="{{ meme['caption'] }}">
                <p>{{ meme['caption'] }}</p>
            </li>
        {% endfor %}
    </ul>
</body>
</html>

This HTML template will display the memes on the meme page using the data from the memes.py file.

Step 9: Testing the meme website
Start the Flask development server by running python app.py in your terminal. Open a web browser and navigate to http://127.0.0.1:5000/memes to view the meme page with the list of memes. You should see the images and captions displayed on the page.

Congratulations! You have successfully built a meme website using Python and Flask. This is just the beginning, and you can continue to add more features and functionality to make your meme website even better. Happy coding!

0 0 votes
Article Rating
33 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@NetworkChuck
2 months ago

Build your own Python Flask website with Linode: https://ntck.co/linode (get a $100 Credit good for 60 days as a new user!!)

💡💡Text walkthrough/Code/Command: https://ntck.co/flask

🔥🔥Join the NetworkChuck Academy!: https://ntck.co/NCAcademy

0:00 ⏩ Intro
0:50 ⏩ What do you need?
2:09 ⏩ What the junk is Flask?
2:56 ⏩ Let’s get started!
8:23 ⏩ Time to build our meme website!
11:33 ⏩ Outro

@brunobondarovsky2247
2 months ago

Such an excellent video. I have started building with a flask, and following your explanation was smooth! Thank you!

@orhasan3851
2 months ago

** 08.24 Problems Solutions **

It's disappointing that someone makes a guide but doesn't maintain it over time (it's only been 2 years..)

So if you got stuck, I'm here for you!

– Problem 1 – Incorrect URL –

Inside your Python file, remove in the following line: " url = 'htt…/gimme' ",

the ".herokuapp" part, and… that's all

– Problem 2 – Missing HTML Code –

I don't know the full style lines he wrote, but the following HTML code will do the trick for you (with a refresh rate of 10sec):

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1">

<meta http-equiv="refresh" content="10; url=http://127.0.0.1:5000" />

<title>Meme Website</title>

<style>

body {

background-color: black;

display: grid;

place-items: center;

color: white;

}

h1 {

font-family: Arial, sans-serif;

color: white;

margin-bottom: 1cm;

}

p {

font-family: Georgia, serif;

color: white;

font-size: 24px;

margin-bottom: 0;

}

</style>

</head>

<body>

<h1>A website to gather some memes !</h1>

<p>Here is your meme! This will refresh in 10 seconds!</p>

<p><img src="{{ meme_pic }}"></p>

<p>Current subreddit: {{ subreddit }}</p>

</body>

</html>

— Bonus —

Show GIFs in your web-page (if available), instead of the large-preview picture!

Inside your Python file, replace the following line: meme_large = response["preview"][-2]

With the original media link (you are welcome to change the variable name as well to keep it relevant to the used data, as long as you update it in the return line as well):

meme_large = response["url"]

Also, add the following html lines to your Style section, as we are no longer taking a constant size picture anymore (feel free to change the maximum size):

img {

max-width: 1000px;

max-height: 1000px;

}

And please @NetworkChuck track people's comments on your videos from time to time, for these exact times when they say there are problems 🙏🏼

@rajdeepverma360
2 months ago

Thank you for this video, I wasn't able to start my flask journey because of all the other typical online tutors, it always seemed a hard but now it seems nothing, you are a great teacher, and Linux influencer.

@GabeNarwhal
2 months ago

Dont work. Getting an error. Dont bother watching this outdated video

@vivac4893
2 months ago

you are awesome.

@poisonsky
2 months ago

I got this working today (7/23/24) after bouncing a few things off of Co-pilot (ChatGPT 4). In this case I'm using port 8888 since this was available on my Ubuntu VM. So the URL would be http://<YOUR-SERVER&gt;:8888/  

There's just two files that Chuck mentions and if you rewrite them like this it should work. If it doesn't then bounce that error off co-pilot!

meme_index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Meme Generator</title>
</head>
<body>
<h1>Random Meme for Athonia</h1>
<img src="{{ meme_pic }}" alt="Meme">

<p>Preview URL: {{ meme_large }}</p>
<p>Subreddit: {{ subreddit }}</p>
</body>
</html>

…and

#!/usr/bin/python3

from flask import Flask, render_template
import requests
import json

app = Flask(__name__)

def get_meme():
url = "https://meme-api.com/gimme"
response = json.loads(requests.request("GET", url).text)
if "preview" in response and len(response["preview"]) >= 2:
meme_large = response["preview"][-2]
else:
meme_large = "default_image_url" # Fallback image URL
subreddit = response["subreddit"]
return meme_large, subreddit

@app.route("/")
def index():
meme_pic,subreddit = get_meme()
return render_template("mem_index.html", meme_pic=meme_pic, subreddit=subreddit)

app.run(host="0.0.0.0", port=8888)

@TiagoVeraCruz
2 months ago

Where are the links for the commands?

@user-bs3ki1dn5l
2 months ago

Could've worked if Reddit didn't make the changes

@MAKEACCOUNT123
2 months ago

you dont need linux for this bro you just need python are you slow

@BVa859
2 months ago

I dont understand why so much arrogancy and idiotic behavior?

@rugwirodev
2 months ago

in case port 80 isn't working , I recommend you 5000, or 5001, it worked for me!

@Noumanii2917
2 months ago

Broo that's amazing plzz give us more videos on flask so we can gradually improve with you🎉❤

@achelias8477
2 months ago

Good content and good presentation skills. I love your vibe! You made me excited to now switch from Node.js to Py 😀

@VGMajor1
2 months ago

Hello i am trying to use this video for learning a bit about web development using Python… But i cant get linode to work and they keep canceling my account. Anyone know a different solution or another website to do this on without it costing much?

@jetboyabordaje3741
2 months ago

Thank you NetworkChuck you are the best

@forheuristiclifeksh7836
2 months ago

10:11

@forheuristiclifeksh7836
2 months ago

8:18

@forheuristiclifeksh7836
2 months ago

5:42

@user-Xgame666
2 months ago

hey NetworkChuck i need more coffee ☕ ☕ and i will make a websites,, thats it 😉