I am trying to develop a small app which will basically plot some graphs based on set of data user provided or requested. The process_order function should be run concurrent different set of data. For some reason I get only the first graph not the second and successive one. I have opened a different browser session with different user got the same result.
Example I tried to open a browser one from IE and another one from Chrome with logged in as user1 with set of 5 inputs - in IE (Expected 5 graphs) and as user2 with set of 20 input - in Chrome (Expected 20 Graphs) I was expecting 2 browser window with 5 graphs from one and 20 graphs from second window:
I am new to python and flask apologies if its something have already asked/answered in different questions
app = Flask(__name__)
plot = None
my_session = None
session_id = None
#app.route('/')
def home():
if not session.get('logged_in'):
return render_template('login.html')
else:
return render_template('template.html')
#app.route('/login', methods=['POST'])
def do_admin_login():
if request.form['password'] == 'password' and request.form['username'] in 'admin' :
session['logged_in'] = True
my_session = Bot(request.form['username'])
my_session.session_id = request.form['username']
session['user'] = request.form['username']
return render_template('template.html')
else:
flash('wrong password!')
return home()
#app.route("/ask", methods=['POST','GET'])
def ask():
string = str(request.form['message'])
res = my_session.process(string)
return jsonify({'status':'OK','answer':bot_res})
class Bot():
#Define user level
def __init__(self,session_id):
self.return_string = ""
self.session_id = session_id
def process(self, string):
self.session_id = session['user']
self.string = string
self.return_string = self.process_order() # This method I would like to execute as concurrent at the same time for multiple users/session with different set ot data
return self.return_string
def process_order(self):
self.plot = Plot()
self.plot.global_url = range(5)
self.i = 0
self.inputs = [] #tuples
self.number = range(5)
self.url_values = zip(self.number,self.inputs)
self.pool = Pool()
self.func = partial(self.plot.do_plot,self.var1)
self.pool.map(self.func,self.url_values)
self.pool.close()
self.pool.join()
process_confirmation = "Your request is complete"
return process_confirmation
class Plot():
def __init__(self):
pass
def do_plot(self, var1):
self.number, self.url = plot_values
self.var1 = var1
fig = plt.figure(self.number)
self.line = str(self.url[1])
self.res = urllib.request.urlopen(self.line)
plt.imshow(plt.imread(self.res))
self.file_name = "%03d.png"%(self.number,)
plt.savefig(self.file_name)
plt.close()
if __name__ == "__main__":
session_id = None
app.secret_key = os.urandom(12)
my_session = Bot(session_id)
app.run(host='0.0.0.0', port=80)
If the problem you are having is that individual requests take a long time, then your problem might stem from using flasks builtin server.
You can try deploying your app with gevent:
http://flask.pocoo.org/docs/1.0/deploying/wsgi-standalone/#gevent
Related
Guy, I need your help. Since I'm newbie and I'm making my first app in Django I came to an issue while testing my app. There is problem with testing views, and since tested manually everything works fine problem occurs while testing automatition.
I think the issue may be related to POST / GET requests because I made things in way that, most things are based on GET, even those which change things in DB. POST request is reserved only to forms. When I start tests, every action that is made seems lacking-effect like those GET requests don't work.
Ok here comes the code:
Views:
#login_required
def new(request):
if request.method == "POST":
player = Player.objects.get(name=request.user)
hosted = Game(host=player.nick)
form = CreateGame(instance=hosted, data=request.POST)
if form.is_valid():
form.save()
return redirect("home", name="new_room")
#login_required
def delete_room(request, id):
game = Game.objects.get(id=id)
player = Player.objects.get(name=request.user)
if player.nick == game.host and game.how_many_players_ready == 0:
if not game.is_played:
game.delete()
return redirect("home", name="game_deleted")
else:
return redirect('detail', id=game.id)
else:
return redirect('detail', id=game.id)
Tests:
class TestViews(TestCase):
def setUp(self):
self.client = Client()
self.user = User.objects.create_user(username='testuser', password='12345')
self.user2 = User.objects.create_user(username='testuser2', password='12345')
usr = self.user
self.client.login(username='testuser', password='12345')
self.player = Player.objects.create(name=usr, parent = usr.username, nick = 'nie')
def test_create_many_rooms(self):
#this one works -> POST
self.new_room=reverse('new_room')
self.client.post(self.new_room, {'name' :'mariaczi', 'host':'mario'})
self.client.post(self.new_room, {'name': 'mariaczi2','host':'mario'})
self.client.post(self.new_room, {'name': 'mariaczi3', 'host': 'mario'})
suma = Game.objects.all().count()
self.assertEquals(suma,3)
def test_host_delete_empty_room(self):
#this one not
game = Game.objects.create(name='empty', host='testuser', is_played=False, max_players=4)
self.delete_room = reverse('delete_gam', args=[game.id])
self.client.get(self.delete_room, follow=True)
suma = Game.objects.all().count()
self.assertEquals(suma,0)
OUTCOME: ======================================================================
FAIL: test_host_delete_empty_room (game.tests.test_views.TestViews)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/dottore/PycharmProjects/Nowa_gra/Nova_gra/game/tests/test_views.py", line 53, in test_host_delete_empty_room
self.assertEquals(suma,0)
AssertionError: 1 != 0
Models:
class Game(models.Model):
name = models.CharField(max_length=150)
host = models.CharField(max_length=10)
is_played = models.BooleanField(default = False)
max_players = models.IntegerField(default=4)
who_is_ready = models.ManyToManyField(Player, related_name="guys_ready", blank=True)
who_is_playing = models.ManyToManyField(Player, related_name="guys_playing", blank=True)
turn = models.IntegerField(default=1)
turn_of_player = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='czyja_tura', blank=True, null=True)
#property
def how_many_players_ready(self):
return self.who_is_ready.count()
#property
def how_many_players_playing(self):
return self.who_is_playing.count()
#property
def players_ready(self):
return list(self.who_is_ready.all())
#property
def players_playing(self):
return list(self.who_is_playing.all())
#property
def players_playing_str(self):
res = [i.nick for i in self.who_is_playing.all()]
return res
#property
def first_player(self):
return self.players_playing[0]
#property
def second_player(self):
return self.players_playing[1]
#property
def third_player(self):
return self.players_playing[2]
#property
def forth_player(self):
return self.players_playing[3]
#property
def next_player(self):
x = self.players_playing.index(self.turn_of_player)
nast= x+1
if nast > (self.how_many_players_playing - 1):
self.turn +=1
self.save()
return self.players_playing[0]
else:
return self.players_playing[x+1]
def __str__(self):
return self.name
Where is the TRICK? Shall I always handle things with database changes other way then generating GET?
There is no trick here... I think the Game object is not getting delete, your delete_room has many if-else's. Common debugging technique is to put a print statement in each if else condition to see which path it's taking.
My suspicion is on first part of this if condition,
if player.nick == game.host this will result in "nie" == "testuser"
which are not equal. But find it yourself using print statements.
I have defined two functions in leaderboard.py, insertData(xpos, ypos, data) and indexThing(row, column). Although I am able to insert data with the insert data function, I am unable to index values in server.py. I have tried indexing directly in server.py with set values and I still received 'None'. How can I go about troubleshooting this?
server.py:
from flask import Flask, request, render_template
import leaderboard
app = Flask(__name__)
#app.route("/script", methods=['POST'])
def script():
input_string = request.form['data']
chose = input_string[:-4]
chose = chose.replace('http://10.0.1.36:5000/static/images/Girls/', 'G')
chose = chose.replace('http://10.0.1.36:5000/static/images/Boys/', 'B')
print (leaderboard.indexThing(22,3)) ##THIS RETURNS NONE
if 'G' in chose:
chose = int(chose[1:len(chose)])
print chose
total = leaderboard.indexThing(chose, 3)
wins = leaderboard.indexThing(chose, 4)
print wins ##THIS RETURNS NONE
print total ##THIS RETURNS NONE
elif 'B' in chose:
chose = int(chose[1:len(chose)])
print chose
total = leaderboard.indexThing(chose, 12)
wins = leaderboard.indexThing(chose, 13)
print wins ##THIS RETURNS NONE
print total ##THIS RETURNS NONE
return "backend response"
#app.route('/')
def static_page():
return render_template('index.html')
#app.route('/boys.html')
def static_page2():
return render_template('boys.html')
#app.route('/girls.html')
def static_page3():
return render_template('girls.html')
if __name__ == "__main__":
app.run(host='10.0.1.36', port=5000, debug=True)
leaderboard.py
#coding=utf-8
import gspread
from oauth2client.service_account import ServiceAccountCredentials
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('static/client_secret.json', scope)
client = gspread.authorize(creds)
sheet = client.open('Rate data').sheet1
def insertData(xpos, ypos, data):
sheet.update_cell(xpos, ypos, data)
def indexThing(row, column):
sheet.cell(row, column).value
Make sure all the types in all the different python functioms are consistent. Same for the Google sheets.
For example, for this line I'd try;
sheet.cell(int(row), (int)column).value
Also make sure you're actually getting a return value from the sheet.cell call. Eg what is the type of just the
sheet.cell(int(row), (int)column)
Is it what youre expecting?
I have a flask web application which has two methods. I need to access the summary variable which is in method 1 inside method 2. the following is what I have done. But it doesn't seem to work out for me.
Method 1
app = Flask(__name__)
#app.route('/templates', methods=['POST'])
def original_text_form():
title = "Summarizer"
text = request.form['input_text'] # Get text
max_value = sent_tokenize(text)
num_sent = int(request.form['num_sentences']) # Get number of sentence required in summary
sum1 = summarize()
summary = sum1.get_summary(text, num_sent)
print(summary)
return render_template("index.html", title = title, original_text = text, output_summary = summary, num_sentences = max_value)
Method 2
#app.route('/savetextfile', methods=['POST'])
def saveToFile():
x = original_text_form
with open('/Users/johnsriskandarajah/Documents/summarizer-master/summary.txt', 'wb') as filehandle:
filehandle.write(x.summary)
return render_template("index.html", My_Function=saveToFile)
Why not use a class to group similar functions and allow access to otherwise locally-scoped variables?
app = Flask(__name__)
class Foo():
def __init__(self):
// do something when initialised
app.route('/method1')
def method1(self):
self.summary = something
app.route('/method2)
def method2(self):
function(self.summary)
Of course, I hate resorting to using the time of busy StackExchange members to solve my issues, but I have asked in the forums from which I retrieved this code to explain how the mechanism works, but there has been absolutely no response.
My question should probably be quite simple (not for myself, as I am what you would call a web development amateur). I have this code (not my own) for the backend a basic blog. But there is one thing that I am not quite understanding. In one of the HTML files, there is a line that has {{user.name}}, which gets the username of the person currently logged in and posts it in the corner of the page. The {{}} is just Jinja2 syntax that prints a python expression to the template (or so I'm told).
How can I get the username of the user logged in within the Python file? What I am currently trying to do in my own web application, is obtain the username of the user logged in and Query the Google Datastore for the information regarding the user and put in on a profile page, like so:
class Profile(BlogHandler):
def render_profile(self):
signatory = user.name
signedevents = db.GqlQuery("SELECT event FROM Signatories WHERE username IN (signatory)")
self.render("profile.html", signedevents=signedevents)
def get(self):
if self.user:
self.render_profile()
else:
self.redirect('/')
But whenever I try this, I always get an error. Is there something else that should go in place of user.name?
Blog code (I am sure the answer is somewhere in the Handler class but I simply cannot figure out what the issue is):
import os
import re
import random
import hashlib
import hmac
from string import letters
import webapp2
import jinja2
from google.appengine.ext import db
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
autoescape = True)
secret = 'fart'
def render_str(template, **params):
t = jinja_env.get_template(template)
return t.render(params)
def make_secure_val(val):
return '%s|%s' % (val, hmac.new(secret, val).hexdigest())
def check_secure_val(secure_val):
val = secure_val.split('|')[0]
if secure_val == make_secure_val(val):
return val
class BlogHandler(webapp2.RequestHandler):
def write(self, *a, **kw):
self.response.out.write(*a, **kw)
def render_str(self, template, **params):
params['user'] = self.user
return render_str(template, **params)
def render(self, template, **kw):
self.write(self.render_str(template, **kw))
def set_secure_cookie(self, name, val):
cookie_val = make_secure_val(val)
self.response.headers.add_header(
'Set-Cookie',
'%s=%s; Path=/' % (name, cookie_val))
def read_secure_cookie(self, name):
cookie_val = self.request.cookies.get(name)
return cookie_val and check_secure_val(cookie_val)
def login(self, user):
self.set_secure_cookie('user_id', str(user.key().id()))
def logout(self):
self.response.headers.add_header('Set-Cookie', 'user_id=; Path=/')
def initialize(self, *a, **kw):
webapp2.RequestHandler.initialize(self, *a, **kw)
uid = self.read_secure_cookie('user_id')
self.user = uid and User.by_id(int(uid))
def render_post(response, post):
response.out.write('<b>' + post.subject + '</b><br>')
response.out.write(post.content)
class MainPage(BlogHandler):
def get(self):
self.write('Hello, Udacity!')
##### user stuff
def make_salt(length = 5):
return ''.join(random.choice(letters) for x in xrange(length))
def make_pw_hash(name, pw, salt = None):
if not salt:
salt = make_salt()
h = hashlib.sha256(name + pw + salt).hexdigest()
return '%s,%s' % (salt, h)
def valid_pw(name, password, h):
salt = h.split(',')[0]
return h == make_pw_hash(name, password, salt)
def users_key(group = 'default'):
return db.Key.from_path('users', group)
class User(db.Model):
name = db.StringProperty(required = True)
pw_hash = db.StringProperty(required = True)
email = db.StringProperty()
#classmethod
def by_id(cls, uid):
return User.get_by_id(uid, parent = users_key())
#classmethod
def by_name(cls, name):
u = User.all().filter('name =', name).get()
return u
#classmethod
def register(cls, name, pw, email = None):
pw_hash = make_pw_hash(name, pw)
return User(parent = users_key(),
name = name,
pw_hash = pw_hash,
email = email)
#classmethod
def login(cls, name, pw):
u = cls.by_name(name)
if u and valid_pw(name, pw, u.pw_hash):
return u
Everything past here is probably not important, but if the answer cannot be found by only using the code above, please continue.
##### blog stuff
def blog_key(name = 'default'):
return db.Key.from_path('blogs', name)
class Post(db.Model):
subject = db.StringProperty(required = True)
content = db.TextProperty(required = True)
created = db.DateTimeProperty(auto_now_add = True)
last_modified = db.DateTimeProperty(auto_now = True)
def render(self):
self._render_text = self.content.replace('\n', '<br>')
return render_str("post.html", p = self)
class BlogFront(BlogHandler):
def get(self):
posts = greetings = Post.all().order('-created')
self.render('front.html', posts = posts)
class PostPage(BlogHandler):
def get(self, post_id):
key = db.Key.from_path('Post', int(post_id), parent=blog_key())
post = db.get(key)
if not post:
self.error(404)
return
self.render("permalink.html", post = post)
class NewPost(BlogHandler):
def get(self):
if self.user:
self.render("newpost.html")
else:
self.redirect("/login")
def post(self):
if not self.user:
self.redirect('/blog')
subject = self.request.get('subject')
content = self.request.get('content')
if subject and content:
p = Post(parent = blog_key(), subject = subject, content = content)
p.put()
self.redirect('/blog/%s' % str(p.key().id()))
else:
error = "subject and content, please!"
self.render("newpost.html", subject=subject, content=content, error=error)
###### Unit 2 HW's
class Rot13(BlogHandler):
def get(self):
self.render('rot13-form.html')
def post(self):
rot13 = ''
text = self.request.get('text')
if text:
rot13 = text.encode('rot13')
self.render('rot13-form.html', text = rot13)
USER_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$")
def valid_username(username):
return username and USER_RE.match(username)
PASS_RE = re.compile(r"^.{3,20}$")
def valid_password(password):
return password and PASS_RE.match(password)
EMAIL_RE = re.compile(r'^[\S]+#[\S]+\.[\S]+$')
def valid_email(email):
return not email or EMAIL_RE.match(email)
class Signup(BlogHandler):
def get(self):
self.render("signup-form.html")
def post(self):
have_error = False
self.username = self.request.get('username')
self.password = self.request.get('password')
self.verify = self.request.get('verify')
self.email = self.request.get('email')
params = dict(username = self.username,
email = self.email)
if not valid_username(self.username):
params['error_username'] = "That's not a valid username."
have_error = True
if not valid_password(self.password):
params['error_password'] = "That wasn't a valid password."
have_error = True
elif self.password != self.verify:
params['error_verify'] = "Your passwords didn't match."
have_error = True
if not valid_email(self.email):
params['error_email'] = "That's not a valid email."
have_error = True
if have_error:
self.render('signup-form.html', **params)
else:
self.done()
def done(self, *a, **kw):
raise NotImplementedError
class Unit2Signup(Signup):
def done(self):
self.redirect('/unit2/welcome?username=' + self.username)
class Register(Signup):
def done(self):
#make sure the user doesn't already exist
u = User.by_name(self.username)
if u:
msg = 'That user already exists.'
self.render('signup-form.html', error_username = msg)
else:
u = User.register(self.username, self.password, self.email)
u.put()
self.login(u)
self.redirect('/blog')
class Login(BlogHandler):
def get(self):
self.render('login-form.html')
def post(self):
username = self.request.get('username')
password = self.request.get('password')
u = User.login(username, password)
if u:
self.login(u)
self.redirect('/blog')
else:
msg = 'Invalid login'
self.render('login-form.html', error = msg)
class Logout(BlogHandler):
def get(self):
self.logout()
self.redirect('/blog')
class Unit3Welcome(BlogHandler):
def get(self):
if self.user:
self.render('welcome.html', username = self.user.name)
else:
self.redirect('/signup')
class Welcome(BlogHandler):
def get(self):
username = self.request.get('username')
if valid_username(username):
self.render('welcome.html', username = username)
else:
self.redirect('/unit2/signup')
app = webapp2.WSGIApplication([('/', MainPage),
('/unit2/rot13', Rot13),
('/unit2/signup', Unit2Signup),
('/unit2/welcome', Welcome),
('/blog/?', BlogFront),
('/blog/([0-9]+)', PostPage),
('/blog/newpost', NewPost),
('/signup', Register),
('/login', Login),
('/logout', Logout),
('/unit3/welcome', Unit3Welcome),
],
debug=True)
If there is something you need me to clarify, please let me know. Thank you in advance for your help.
OK, you're inheriting BlogHandler.
To get the username info, by following the Unit3Welcome() example, I think you need to change signatory = user.name to signatory = self.user.name
To fill the {{user.name}} field in a jinja2 template it needs to get in the template values dict it receives a user variable (also of dict type) containing a name key (presumably with the respective username). For example: {'user': {'name': 'johndoe'}}.
I'm not familiar neither with how the renderer you use works nor with SQL and how signedevents is filled, so you may need to adapt.
To easily inspect (in debug print style) what actually makes it to the template you can temporarily insert a paragraph like this somewhere in your html: <p>user: ({{ user }})</p> and you should get the dump of the user variable right in your browser :)
Hi I remember this thing with App Engine, maybe it has to do something with the old 'db' datastore. Google now recommends to use 'ndb'.
Since you are also setting cookie you can actually use it to render your user's name in the Welcome page.
This is how I got around it, hope this helps.
class Register(SignUp):
def done(self):
#make sure the user doesn't already exist
u = User.by_name(self.request.get("username"))
if u:
msg = 'That user already exists.'
self.render('signup-form.html', username_exists = msg)
else:
username = self.request.get("username")
password = self.request.get("password")
email = self.request.get("email")
u = User.register(username, password , email)
u.put()
self.login(u)
self.redirect('/blog/welcome')
class Welcome(BlogHandler):
def get(self):
cookie = self.request.cookies.get("user_id")
val = check_secure_val(cookie)
u = User.by_id(int(val))
if u:
print u
self.render('welcome.html', username = u.name)
else:
self.redirect('/blog/signup')
I am creating a captcha just for an exercise. The creation of the captcha images seem fine. But every time I try validating the captcha challenge entered by the user, the validation is done against the next captcha. I am stuck at how to go with this.
Function for creating captcha images- captcha.py
import random
import Image
import ImageFont
import ImageDraw
import ImageFilter
import JpegImagePlugin
import PngImagePlugin
def gen_captcha(text, fnt, fnt_sz, file_name, fmt='JPEG'):
fgcolor = random.randint(0,0xff0000)
bgcolor = fgcolor ^ 0xffffff
font = ImageFont.truetype(fnt,fnt_sz)
dim = font.getsize(text)
im = Image.new('RGB', (dim[0]+5,dim[1]+5), bgcolor)
d = ImageDraw.Draw(im)
x, y = im.size
r = random.randint
for num in range(100):
d.rectangle((r(0,x),r(0,y),r(0,x),r(0,y)),fill=r(0,0xffff00))
d.text((3,3), text, font=font, fill=fgcolor)
im = im.filter(ImageFilter.EDGE_ENHANCE_MORE)
im.save(file_name)
signup function from views.py
#app.route('/signup', methods = ['GET', 'POST'])
def signup():
if g.user is not None and g.user.is_authenticated():
return redirect(url_for('index'))
words = open('app/corncob_caps.txt').readlines()
captcha_word = words[random.randint(1,len(words))]
captcha_filename = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(10)) + '.jpg'
captcha.gen_captcha(captcha_word.strip(), 'app/os.ttf', 25, 'app/static/' + captcha_filename + '')
form = SignUpForm(captcha_word)
if form.validate_on_submit() == False:
return render_template('signup.html', form = form, filename = captcha_filename)
else:
user = User(form.email.data, form.password.data)
db.session.add(user)
db.session.commit()
flash('You have successfully signed up.')
flash('You may login now.')
return redirect(url_for('login'))
return render_template('signup.html', form = form, filename = captcha_filename)
I am passing the captcha_word to my form class. The form class is:
class SignUpForm(Form):
email = EmailField('Email Address', validators = [email()])
password = PasswordField('Password', validators = [Required('Please enter a valid password between 8 and 30 characters.'), Length(min = 8, max = 30)])
captcha = TextField('Captcha', validators = [Required('You must enter the challenge captcha.')])
submit = SubmitField('Create Account')
captcha_word = ''
def __init__(self, word, *args, **kwargs):
Form.__init__(self, *args, **kwargs)
self.get_word(word)
def get_word(self, word):
self.captcha_word = word
def validate(self):
if not Form.validate(self):
return False
elif self.captcha_word != self.captcha.data.upper():
print self.captcha_word
print self.captcha.data.upper()
self.captcha.errors.append("Wrong captcha!")
return False
user = self.get_user()
if user:
self.email.errors.append("That email is already taken.")
return False
else:
return True
def get_user(self):
return User.query.filter_by(email = self.email.data.lower()).first()
I inserted the two print statements inside to see why the comparison was coming wrong. The first print showed the next captcha whereas the print self.captcha.data.upper() displayed the user entered data.
I am not sure, but it seems the signup route is being called twice. But I don't know how to fix this. Any ideas?
If you need to use a captcha, you can use the feature that's already built into Flask-WTF and save yourself reinventing the wheel.
If you do want to reinvent the wheel, then the main problem you're having is that you're recreating the captcha when the user submits the form, you have no way to remember and refer to the old value.
So this is how it's working at the moment:
User goes to sign in, you generate a captcha, then because they haven't submitted a form, it shows the sign in form including the captcha picture.
User fills in the form and hits the submit button- this loads the signup view again,creates a new random captcha, then goes down the form submitted
logic path, so when you compare the user captcha data to the current captcha data, it doesn't match.
So you're missing persistence, the captcha you generate the first time round doesn't get held anywhere, so when the user submits you've got no way to refer back to it. So you need to store that captcha word somewhere. You could simply just store that captcha word in the user's session and use that to validate against when you need to, or perhaps sign it with itsdangerous and store it in the form itself as a hidden field?
Code Example:
This just takes your code and adjusts it a little to store the value in the session-- not tested, and can definitely been improved, but should work:
#app.route('/signup', methods = ['GET', 'POST'])
def signup():
if g.user is not None and g.user.is_authenticated():
return redirect(url_for('index'))
if request.method == 'post':
captcha_word = session["captcha"]
else:
words = open('app/corncob_caps.txt').readlines()
captcha_word = words[random.randint(1,len(words))]
session["captcha"] = captcha_word
captcha_filename = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(10)) + '.jpg'
captcha.gen_captcha(captcha_word.strip(), 'app/os.ttf', 25, 'app/static/' + captcha_filename + '')
form = SignUpForm(captcha_word)
if form.validate_on_submit() == False:
return render_template('signup.html', form = form, filename = captcha_filename)
else:
user = User(form.email.data, form.password.data)
db.session.add(user)
db.session.commit()
flash('You have successfully signed up.')
flash('You may login now.')
return redirect(url_for('login'))
return render_template('signup.html', form = form, filename = captcha_filename)