4
\$\begingroup\$

I'm new to programming and in back-end. Right now I'm trying to learn flask, so I wrote a very simple website that currently encrypts and decrypts the message using RSA and DES.

I feel like my app.py file is just bad and should do it much better. I mean, there're a lot of repeating code like this:

@app.route('/rsa_encrypt', methods=['GET', 'POST'])
def RSA_enc():
    global get_form
    if request.method == "GET":
        get_form = True
        return render_template('rsa_encrypt.html', gf=get_form)
    else:
        get_form = False
        rsa = RSA(request.form.get('pt'), p=request.form.get('p'),
                  q=request.form.get('q'), e=request.form.get('e'))
        return render_template('rsa_encrypt.html', gf=get_form, rsa=rsa, gspn=gspn)

I tried to write some decorators for those routes, but they didn't work well.

Can you take a look and tell me what should I do better? It works but I think not as well as it should.

app.py

from flask import Flask, render_template, request, url_for, jsonify
from ciphers import RSA, DES
from prime import generate_semiprime_number as gspn

app = Flask(__name__)
get_form = None

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

@app.route('/rsa_encrypt', methods=['GET', 'POST'])
def RSA_enc():
    global get_form
    if request.method == "GET":
        get_form = True
        return render_template('rsa_encrypt.html', gf=get_form)
    else:
        get_form = False
        rsa = RSA(request.form.get('pt'), p=request.form.get('p'),
                  q=request.form.get('q'), e=request.form.get('e'))
        return render_template('rsa_encrypt.html', gf=get_form, rsa=rsa, gspn=gspn)

@app.route('/rsa_decrypt', methods=['GET', 'POST'])
def RSA_dec():
    global get_form
    if request.method == "GET":
        get_form = True
        return render_template('rsa_decrypt.html', gf=get_form)
    else:
        get_form = False
        ct = [int(x) for x in request.form.get('ct')[1:-1].split(',')]
        rsa = RSA(ciphertext=ct, p=request.form.get('p'),
                  q=request.form.get('q'), e=request.form.get('e'))
        return render_template('rsa_decrypt.html', gf=get_form, rsa=rsa)

@app.route('/des_encrypt', methods=['GET', 'POST'])
def DES_enc():
    global get_form
    if request.method == "GET":
        get_form = True
        return render_template('des_encrypt.html', gf=get_form)
    else:
        get_form = False
        des = DES(request.form.get('pt'), user_key=request.form.get('key'))
        return render_template('des_encrypt.html', gf=get_form, des=des)

@app.route('/des_decrypt', methods=['GET', 'POST'])
def DES_dec():
    global get_form
    if request.method == "GET":
        get_form = True
        return render_template('des_decrypt.html', gf=get_form)
    else:
        get_form = False
        des = DES(ciphertext=request.form.get('ct'), user_key=request.form.get('key'))
        return render_template('des_decrypt.html', gf=get_form, des=des)

@app.route('/gpsn', methods=['POST'])
def _gpsn():
    return jsonify({'result' : str(gspn(request.form['bits']))})


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

Other files repository. It's also hosted so you can quickly take a look.

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

Your main issue is (as you've already noticed) one of code repetition. Some simple helper methods here will do the trick; caveat - untested:

from flask import Flask, render_template, request, url_for, jsonify
from ciphers import RSA, DES
from prime import generate_semiprime_number as gspn

app = Flask(__name__)
get_form = None

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

def do_rsa(encrypting):
    global get_form

    direction = 'en' if encrypting else 'de'
    tmpl = f'rsa_{direction}crypt.html'

    if request.method == 'GET':
        return render_template(tmpl, gf=True)

    kwargs = {'p': request.form.get('p'),
              'q': request.form.get('q'),
              'e': request.form.get('e')}
    if encrypting:
        rsa = RSA(request.form.get('pt'), **kwargs)
    else:
        ct = [int(x) for x in request.form.get('ct')[1:-1].split(',')]
        rsa = RSA(ciphertext=ct, **kwargs)

    kwargs = {}
    if encrypting:
        kwargs['gpsn'] = gpsn
    return render_template(tmpl, gf=False, rsa=rsa, **kwargs)

@app.route('/rsa_encrypt', methods=('GET', 'POST'))
def RSA_enc():
    return do_rsa(True)

@app.route('/rsa_decrypt', methods=('GET', 'POST'))
def RSA_dec():
    return do_rsa(False)

def do_des(encrypting):
    global get_form

    direction = 'en' if encrypting else 'de'
    tmpl = f'des_{direction}crypt.html'

    if request.method == 'GET':
        return render_template(tmpl, gf=True)

    kwargs = {'user_key': request.form.get('key')}
    if encrypting:
        des = DES(request.form.get('pt'), **kwargs)
    else:
        des = DES(ciphertext=request.form.get('ct'), **kwargs)

    return render_template(tmpl, gf=False, des=des)


@app.route('/des_encrypt', methods=('GET', 'POST'))
def DES_enc():
    return do_des(True)

@app.route('/des_decrypt', methods=('GET', 'POST'))
def DES_dec():
    return do_des(False)

@app.route('/gpsn', methods=('POST',))
def _gpsn():
    return jsonify({'result' : str(gspn(request.form['bits']))})


if __name__ == '__main__':
    app.run()
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.