2015-09-19 16 views
6

Ok, quindi sono nuovo nel pallone e voglio sapere quali oggetti o strumenti vorrei usare per farlo. Voglio creare un modulo, in cui l'utente immette del testo, fa clic su un pulsante di invio, quindi il testo inviato viene associato come una stringa python e ha una funzione eseguita su di esso e il testo viene quindi reinserito sul Web pagina che stanno visualizzando con il valore di ritorno di quella funzione che ha attraversato. Ecco un esempio: moduloCome compilare un post in maschera

html:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title></title> 
</head> 
<body> 
<form action = "/" method="get"> 
    <input type="text" name="mail" size="25"> 
    <input type="submit" value="Submit"> 
</form> 

<textarea cols="50" rows="4" name="result"></textarea> 

</body> 
</html> 

quindi qui è ciò che credo dovrebbe essere la funzione URL dovrebbe assomigliare

@app.route('/', methods=['GET', 'POST']) 
    def form(): 
     if request.method == 'GET': 
      input_text = request.data #step to bind form text to python string 
       new_text = textfunction(input_text) #running the function on the retrieved test. 
       return (new_text) # no idea if this is write, but returns text after modification. 

Quale sarebbe il modo migliore per impostare questa funzione ? Sarebbe corretto inserire una variabile come valore per l'input html? Ho bisogno di aiuto su questo.

risposta

8

In pratica, ciò che si vuole fare è avere un blocco nel modello che è incluso solo se la variabile ha un valore impostato. Vedere il seguente esempio

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title></title> 
</head> 
<body> 
<form action = "/" method="get"> 
    <input type="text" name="mail" size="25"> 
    <input type="submit" value="Submit"> 
</form> 

{% if result %} 
<textarea cols="50" rows="4" name="result">{{ result }}</textarea> 
{% endif %} 

</body> 
</html> 

e poi nel codice python

@app.route('/', methods=['GET', 'POST']) 
def index(result=None): 
    if request.args.get('mail', None): 
     result = process_text(request.args['mail']) 
    return render_template('index.html', result=result) 


def process_text(text): 
    return "FOO" + text 
+0

grazie mille! una domanda veloce, cosa vuol dire lo slot None in request.args.get ('mail', None)? –

+0

request.args.get ('mail', None) restituirà il valore di 'mail' nel dict se è impostato, altrimenti restituisce None che è falso. request.args è un dict dei parametri della query in una richiesta get –