python

Creating a Simple Pastebin Service in Python and Flask

Learn how to build a functional pastebin service using Python and Flask. This tutorial covers web development basics, file handling, and syntax highlighting.

This post builds a simple Pastebin service with Python and Flask. Pastebin is a popular web app for storing plain text or code snippets for a while. We’ll build a basic version that lets users paste text, pick a programming language, and get a URL to share the paste. I also made a YouTube video about this build.

A pastebin is a Flask route that writes a file with a random ID and hands back a URL that reads it.

Getting started

Before writing the application, set up the environment:

  1. First, create a virtual environment in the project directory.
bash
python -m venv venv
  1. With the virtual environment created, activate it and install the libraries this project needs.
bash
pip install Flask shortuuid pygments

We’ll use shortuuid to generate a unique ID for each paste, and pygments for syntax highlighting.

  1. With the libraries installed, create the necessary files and folders.
bash
mkdir -p pastes templates static && touch index.py templates/index.html static/styles.css

This is how your folder structure should look:

bash
pastebin/│├── app.py├── pastes/├── templates/│   └── index.html└── static/    └── styles.css

The pastes directory stores the text file for each paste. The templates directory holds our HTML templates, and the static directory holds the CSS for styling.

With the environment set up, it’s time to write the code.

Writing the code

Create a file named index.py and add the following code:

With the Flask app written, create the HTML template in templates/index.html and the styles in static/style.css.

  • templates/index.html

  • static/style.css

Before running the application, here’s how the code works.

Code breakdown

  1. First, import the libraries and modules. Flask is the web framework, shortuuid generates unique IDs, and Pygments handles syntax highlighting. This also sets up the pastes/ directory.
python
from flask import Flask, request, render_template, abort
import shortuuid
import os
from pygments import highlight
from pygments.lexers import get_lexer_by_name, get_all_lexers
from pygments.formatters import HtmlFormatter

app = Flask(__name__)

PASTE_DIR = 'pastes'
if not os.path.exists(PASTE_DIR):
    os.makedirs(PASTE_DIR)
  1. This function retrieves all the programming languages Pygments supports for syntax highlighting and returns them as a sorted list of tuples.
python
def get_language_options():
    return sorted([(lexer[1][0], lexer[0]) for lexer in get_all_lexers() if lexer[1]])
  1. This is the main route for the application. If the request method is POST (the user submitted the form), it saves the content and language to a new file under a unique ID, then generates and shows the paste’s URL. If the request method is GET, it just renders the form.
python
@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        content = request.form['content']
        language = request.form['language']
        paste_id = shortuuid.uuid()
        file_path = os.path.join(PASTE_DIR, paste_id)

        with open(file_path, 'w') as f:
            f.write(f"{language}\n{content}")

        paste_url = request.url_root + paste_id
        return render_template('index.html', paste_url=paste_url, languages=get_language_options())

    return render_template('index.html', languages=get_language_options())

This route handles viewing a specific paste. It reads the paste file, applies syntax highlighting with pygments, and renders the highlighted content.

python
@app.route('/<paste_id>')
def view_paste(paste_id):
    file_path = os.path.join(PASTE_DIR, paste_id)
    if not os.path.exists(file_path):
        abort(404)

    with open(file_path, 'r') as f:
        language = f.readline().strip()
        content = f.read()

    lexer = get_lexer_by_name(language, stripall=True)
    formatter = HtmlFormatter(linenos=True, cssclass="source")
    highlighted_content = highlight(content, lexer, formatter)
    highlight_css = formatter.get_style_defs('.source')

    return render_template('index.html', paste_content=highlighted_content, highlight_css=highlight_css)

With everything explained, run the application: python index.py

Wrapping up

You’ve built a simple Pastebin service with Python and Flask. It lets users paste text, pick a programming language, and share the paste through a unique URL. You can extend it with features like expiration times for pastes, user authentication, or a database to store pastes more efficiently.

If you have feedback, leave a comment below, or send me an email if you’d rather not comment publicly.

Announcements

  • I started a YouTube channel a year ago; if you want more video series like this, feel free to subscribe.
  • I’m also open for Python consulting. If you have an interesting Python project, or need advice on tech, send me an email.
  • Thanks for reading and supporting my work.

If you liked this post, you can support my work by buying me a coffee. Your support means a lot. If you share this on X, tag me @muhammad_o7. You can also follow me on LinkedIn.

Want new posts in your inbox? Subscribe by email or follow the RSS feed.