0

I have an HTML form that asks users for their emails, and a .txt file where the emails are stored line by line. How do I show on my website, a "counter", like so:

"Join x number of people who already signed up!"

Where x is an int that counts the number of emails in the .txt file? I am using flask for my web server, combined with HTML, CSS, and Javascript.

Ajax1234
  • 69,937
  • 8
  • 61
  • 102
Evan Yang
  • 125
  • 1
  • 8
  • Get the number of emails with the following: `emails_count = sum(1 for line in open('members.txt'))`, change members.txt to your file dir. – Yassine Qoraiche Jun 21 '18 at 17:14

1 Answers1

1

In your route that serves the signup form, read the file line by line, find the length of the resulting list, and pass the result to flask.render_template:

signup.html:

<html>
  <body>     
    <p> Join {{num}} other user{{plural}} who have already signed up!</p>
    <form action = '/get_data' method='POST'> 
      <input type='email' name='email' placeholder='enter your email'>
      <input type='submit'>Submit</input>  
    </form>
  <body>
</html>

In the route:

@app.route('/signup', methods=['GET'])
def signup():
   current_users = len([i for i in open('filename.txt')])
   return flask.render_template('signup.html', num = current_users, plural = '' if current_users == 1 else 's')

@app.route('/get_data', methods=['POST'])
def get_email():
   with open('filename.txt', 'a') as f:
     f.write('{}\n'.format(flask.request.form["email"]))
   return '<h1>Thanks!</h1>'
Ajax1234
  • 69,937
  • 8
  • 61
  • 102