I got this error in my code: return getattr(obj, attribute) jinja2.exceptions.UndefinedError: ‘base64’ is undefined

  File "/Users/bkalpa/Library/Python/3.9/lib/python/site-packages/flask/app.py", line 1498, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/bkalpa/Library/Python/3.9/lib/python/site-packages/flask/app.py", line 1476, in wsgi_app
    response = self.handle_exception(e)
  File "/Users/bkalpa/Library/Python/3.9/lib/python/site-packages/flask/app.py", line 1473, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/bkalpa/Library/Python/3.9/lib/python/site-packages/flask/app.py", line 882, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/bkalpa/Library/Python/3.9/lib/python/site-packages/flask/app.py", line 880, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/bkalpa/Library/Python/3.9/lib/python/site-packages/flask/app.py", line 865, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)  # type: ignore[no-any-return]
  File "/Users/bkalpa/Desktop/Desktop/Capstone - 2/app.py", line 63, in view_messages
    return render_template('message.html', messages=user_messages, decrypt=decrypt)
  File "/Users/bkalpa/Library/Python/3.9/lib/python/site-packages/flask/templating.py", line 150, in render_template
    return _render(app, template, context)
  File "/Users/bkalpa/Library/Python/3.9/lib/python/site-packages/flask/templating.py", line 131, in _render
    rv = template.render(context)
  File "/Users/bkalpa/Library/Python/3.9/lib/python/site-packages/jinja2/environment.py", line 1304, in render
    self.environment.handle_exception()
  File "/Users/bkalpa/Library/Python/3.9/lib/python/site-packages/jinja2/environment.py", line 939, in handle_exception
    raise rewrite_traceback_stack(source=source)
  File "/Users/bkalpa/Desktop/Desktop/Capstone - 2/templates/message.html", line 13, in top-level template code
    <strong>Decrypted Message:</strong> {{ decrypt(message['message'], base64.b64decode(message['key'])) }}<br>
  File "/Users/bkalpa/Library/Python/3.9/lib/python/site-packages/jinja2/environment.py", line 487, in getattr
    return getattr(obj, attribute)
jinja2.exceptions.UndefinedError: 'base64' is undefined

My code for:

app.py

from flask import Flask, render_template, request, redirect, url_for, session
import os
import base64

app = Flask(__name__)
app.secret_key = 'supersecretkey'

# In-memory storage for profiles and messages
profiles = {}
messages = []

# Generate a random key
def generate_key(length):
    return os.urandom(length)

# Encrypt the message
def encrypt(message, key):
    message_bytes = message.encode('utf-8')
    encrypted_bytes = bytes([mb ^ kb for mb, kb in zip(message_bytes, key)])
    return base64.b64encode(encrypted_bytes).decode('utf-8')

# Decrypt the message
def decrypt(encrypted_message, key):
    encrypted_bytes = base64.b64decode(encrypted_message.encode('utf-8'))
    decrypted_bytes = bytes([eb ^ kb for eb, kb in zip(encrypted_bytes, key)])
    return decrypted_bytes.decode('utf-8')

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

@app.route('/create_profile', methods=['POST'])
def create_profile():
    username = request.form['username']
    if username not in profiles:
        profiles[username] = {'messages': []}
    return redirect(url_for('index'))

@app.route('/send_message', methods=['POST'])
def send_message():
    sender = request.form['sender']
    receiver = request.form['receiver']
    message = request.form['message']
    
    if receiver not in profiles:
        return "Receiver profile does not exist", 400

    key = generate_key(len(message))
    encrypted_message = encrypt(message, key)

    # Store the encrypted message and key with the receiver
    profiles[receiver]['messages'].append({'from': sender, 'message': encrypted_message, 'key': base64.b64encode(key).decode('utf-8')})
    
    return redirect(url_for('index'))

@app.route('/view_messages/<username>')
def view_messages(username):
    if username not in profiles:
        return "Profile does not exist", 400

    user_messages = profiles[username]['messages']
    return render_template('message.html', messages=user_messages, decrypt=decrypt)

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

Index.html

<!DOCTYPE html>
<html>
<head>
    <title>One-Time Pad Encryption</title>
</head>
<body>
    <h1>Create Profile</h1>
    <form method="POST" action="/create_profile">
        <input type="text" name="username" placeholder="Username" required>
        <button type="submit">Create</button>
    </form>

    <h1>Send Message</h1>
    <form method="POST" action="/send_message">
        <select name="sender">
            {% for username in profiles %}
                <option value="{{ username }}">{{ username }}</option>
            {% endfor %}
        </select>
        <select name="receiver">
            {% for username in profiles %}
                <option value="{{ username }}">{{ username }}</option>
            {% endfor %}
        </select>
        <input type="text" name="message" placeholder="Message" required>
        <button type="submit">Send</button>
    </form>

    <h1>Profiles</h1>
    <ul>
        {% for username in profiles %}
            <li><a href="/view_messages/{{ username }}">{{ username }}</a></li>
        {% endfor %}
    </ul>
</body>
</html>

message.html

<!DOCTYPE html>
<html>
<head>
    <title>Messages</title>
</head>
<body>
    <h1>Messages</h1>
    <ul>
        {% for message in messages %}
            <li>
                <strong>From:</strong> {{ message['from'] }}<br>
                <strong>Encrypted Message:</strong> {{ message['message'] }}<br>
                <strong>Decrypted Message:</strong> {{ decrypt(message['message'], base64.b64decode(message['key'])) }}<br>
            </li>
        {% endfor %}
    </ul>
    <a href="/">Back</a>
</body>
</html>

Can you help me to debug this?

New contributor

Bikalpa Adhikari is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật