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.