Come eseguire la validazione di Python da Javascript
Tempo di lettura stimato: 6 minuti
Sempre di più, gli sviluppatori di siti web stanno cercando di fondere diverse tecnologie di programmazione per consentire loro di utilizzare funzionalità che forse non sono disponibili nel linguaggio di programmazione corrente che utilizzano.
Nei post precedenti come passare variabili python a Javascript e come eseguire python direttamente da javascript, abbiamo toccato come usare Python e Javascript in modo intercambiabile per passare dati.
Qui, in questo post del blog, daremo un'occhiata alla convalida dei dati usando Python, con dati catturati da Javascript. Lo scopo qui è di permettere un altro modo di convalidare i dati oltre a fare affidamento su javascript.
Ci sono diverse ragioni per questo:
- Potresti voler usare Python per elaborare i dati e fornire l'output.
- I dati potrebbero essere passati da Python in un database, è necessario eseguire alcuni controlli prima di procedere.
- Python è il tuo linguaggio di base, usi solo Javascript per catturare i dati e passarli da un sito web.
Ci sono quattro controlli di validazione
- Validazione se esiste un nome utente.
- Validazione se è stato inserito un numero in un campo nome utente.
- Convalida di una password inserita.
- Un controllo di convalida per assicurarsi che un indirizzo e-mail inserito sia nel formato corretto.
Abbiamo due file con il codice richiesto come segue:
- app.py ===> Poiché questa applicazione è costruita in Python Flask, questo file contiene la logica per aprire i file del sito web, e contiene i controlli di validazione Python .
- index.html ====> Questo file contiene l'HTML che crea le pagine, le etichette e le caselle di input che appaiono nel browser web. Include anche il Javascript che cattura i dati da passare a Python per la validazione.
Panoramica del codice - App.PY
Di seguito, cercherò di spiegare cosa sta succedendo come segue:
La variabile Regex è usata nella validazione dell'email per controllare se l'email inserita è corretta.
def inputcheck ===> Questo è solo il controllo del nome utente passato ed esegue alcune validazioni su di esso.
def inputvalidation ====> Anche questo controlla il nome utente ma guarda se sono stati inseriti solo numeri o se è vuoto.
def passvalidation ====> In questo pezzo di logica, controlla se la password è vuota, meno di cinque caratteri, è solo numeri.
def emailvalidation ====> Tutto ciò che sta facendo è controllare se i dati ricevuti dal Javascript sono nel formato email corretto. Fa riferimento alla variabile regex di cui sopra, che viene utilizzata per confermare se il formato è corretto o meno.
All'interno di ogni funzione, ci sono dichiarazioni if che sono i controlli di validazione fondamentali usati da Python.
Inoltre, tutti i menu popup usano ctypes, che vi permette di accedere alle librerie di finestre che contengono le caselle di messaggio, personalizzarle e chiamarle all'interno del vostro programma.
import json
import ctypes
import re
from flask import request,redirect,url_for
from flask import Flask, render_template
app = Flask(__name__)
regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
@app.route('/')
def index():
return render_template('index.html')
@app.route('/inputcheck', methods=['GET','POST'])
def inputcheck():
output = request.get_json()
result = json.loads(output) #this converts the json output to a python dictionary
username_list = ['joe','john']
if result['username'] in username_list:
MessageBox = ctypes.windll.user32.MessageBoxW(0, 'Username ' + result['username'] + ' ' + 'exists', "Username check", 0x00001000)
return render_template('various.html')
elif result['username'] == '':
MessageBox = ctypes.windll.user32.MessageBoxW(None, 'You cannot enter an empty value', 'Username check', 0x00001000)
else:
MessageBox = ctypes.windll.user32.MessageBoxW(None, 'Username ' + result['username'] + ' ' + 'does not exist', 'Username check', 0x00001000)
@app.route('/inputvalidation', methods=['GET','POST'])
def inputvalidation():
output = request.get_json()
result = json.loads(output) #this converts the json output to a python dictionary
if result['username'].isdecimal():
MessageBox = ctypes.windll.user32.MessageBoxW(None, 'Your username cannot be numbers',"Number check", 0x00001000)
elif result['username'] == '':
MessageBox = ctypes.windll.user32.MessageBoxW(None, 'The username cannot be empty', "Number check",0x00001000)
else:
MessageBox = ctypes.windll.user32.MessageBoxW(None, 'Your username looks ok', "Number check", 0x00001000)
return render_template('index.html')
@app.route('/passvalidation', methods=['GET','POST'])
def passvalidation():
output = request.get_json()
result = json.loads(output) #this converts the json output to a python dictionary
if result['password'].isdecimal():
MessageBox = ctypes.windll.user32.MessageBoxW(None, 'Your password cannot be numbers',"Password check", 0x00001000)
elif result['password'] == '':
MessageBox = ctypes.windll.user32.MessageBoxW(None, 'The password cannot be empty', "Password empty check",0x00001000)
elif len(result['password']) < 5:
MessageBox = ctypes.windll.user32.MessageBoxW(None, 'Your username should be greater than five characters', "Password length check", 0x00001000)
else:
MessageBox = ctypes.windll.user32.MessageBoxW(None, 'Your password looks ok', "Number check", 0x00001000)
return render_template('index.html')
@app.route('/emailvalidation', methods=['GET','POST'])
def emailvalidation():
output = request.get_json()
result = json.loads(output) #this converts the json output to a python dictionary
if re.search(regex, result['email']):
MessageBox = ctypes.windll.user32.MessageBoxW(None, 'Your email is in the correct format', "Email check", 0x00001000)
else:
MessageBox = ctypes.windll.user32.MessageBoxW(None, 'Your email is invalid, please correct', "Email check", 0x00001000)
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
Panoramica del codice - Index.html
Il codice che segue è il codice della pagina, che permette la cattura dei dati attraverso una pagina HTML del browser web.
Between the <style></style> tags these are the CSS properties that format the labels and buttons on the page.
Within the <div></div> tags are where we create the labels and buttons to show on the screen. Also within these, are the references to the on click event function that should run once the buttons are clicked.
Within the <script></script> tags, this is where the javascript is written which captures the data entered into the input boxes within the <div> tags.
Inoltre, vedrai che all'interno di questo javascript, ci sono sezioni chiamate $.ajax, che è dove i dati catturati dal javascript vengono memorizzati, e poi passati al file di script Python (app.py)
Notate che in ogni ajax si fa riferimento a url:"/APAGENAME". Queste sono le sezioni all'interno dell'app.py a cui vengono passati i dati, e poi la logica Python entra in gioco e convalida i dati.
<html lang="en">
<head>
<title>Data Analytics Ireland</title></head>
<style>
.button1 {
position: absolute;
top: 50%;
left: 55%;
width: 900px;
height: 300px;
margin-left: -300px;
margin-top: -80px;
}
.labels {
position: absolute;
top: 50%;
left: 55%;
width: 900px;
height: 300px;
margin-left: -300px;
margin-top: -150px;
}
</style>
<body>
<div class="labels" id="mem1" >
<label for="username">username:</label> <input type="text" id="username" name="username">
<label for="password">password:</label><input type="text" id="password" name="password">
<label for="email">email:</label><input type="text" id="email" name="password">
</div>
<div class="button1" id="mem2" >
<button type="submit" onclick='myfunction();'>Click here to validate your username</button>
<button type="submit" onclick='myfunctionval();'>Click here to check if a number</button>
<button type="submit" onclick='myfunctionpass();'>Click here to check password</button>
<button type="submit" onclick='myfunctionemail();'>Click here to check your email</button>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
function myfunction() {
const username = document.getElementById("username").value;
const password = document.getElementById("password").value;
const dict_values = {username, password} //Pass the javascript variables to a dictionary.
const s = JSON.stringify(dict_values); // Stringify converts a JavaScript object or value to JSON.
console.log(s); // Prints the variables to console window, which are in the JSON format
//window.alert(s)
$.ajax({
url:"/inputcheck",
type:"POST",
contentType: "application/json",
data: JSON.stringify(s)});
}
</script>
<script>
function myfunctionval() {
const username = document.getElementById("username").value;
const password = document.getElementById("password").value;
const dict_values = {username, password} //Pass the javascript variables to a dictionary.
const s = JSON.stringify(dict_values); // Stringify converts a JavaScript object or value to JSON.
console.log(s); // Prints the variables to console window, which are in the JSON format
//window.alert(s)
$.ajax({
url:"/inputvalidation",
type:"POST",
contentType: "application/json",
data: JSON.stringify(s)});
}
</script>
<script>
function myfunctionpass() {
const username = document.getElementById("username").value;
const password = document.getElementById("password").value;
const dict_values = {username, password} //Pass the javascript variables to a dictionary.
const s = JSON.stringify(dict_values); // Stringify converts a JavaScript object or value to JSON.
console.log(s); // Prints the variables to console window, which are in the JSON format
//window.alert(s)
$.ajax({
url:"/passvalidation",
type:"POST",
contentType: "application/json",
data: JSON.stringify(s)});
}
</script>
<script>
function myfunctionemail() {
const email = document.getElementById("email").value;
const dict_values = {email} //Pass the javascript variables to a dictionary.
const s = JSON.stringify(dict_values); // Stringify converts a JavaScript object or value to JSON.
console.log(s); // Prints the variables to console window, which are in the JSON format
//window.alert(s)
$.ajax({
url:"/emailvalidation",
type:"POST",
contentType: "application/json",
data: JSON.stringify(s)});
}
</script>
</body>
</html>