Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy path__init__.py
More file actions
Latest commit
502 lines (393 loc) · 16 KB
/
Copy path__init__.py
File metadata and controls
502 lines (393 loc) · 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
fromflaskimportFlask, render_template, redirect, \
url_for, request, session, flash, g, make_response, send_file
fromflask.ext.loginimportLoginManager, login_user, logout_user, current_user, login_required
fromfunctoolsimportwraps
importMySQLdb
fromMySQLdbimportescape_stringasthwart
importjson
importdatetime
fromdatetimeimportdatetime,timedelta
fromtimeimportmktime
importos
importtime
importurllib2
fromwtformsimportForm, BooleanField, TextField, PasswordField, validators
frompasslib.hashimportsha256_crypt
fromdbconnectimportconnection
importgc
# Dictates urls and linkage
fromcontent_managementimportContent
importsmtplib
fromflask_mailimportMail, Message
app=Flask(__name__)
app.config.update(
DEBUG=True,
#EMAIL SETTINGS
MAIL_SERVER='smtp.gmail.com',
MAIL_PORT=465,
MAIL_USE_SSL=True,
MAIL_USERNAME='your@gmail.com',
MAIL_PASSWORD='yourpassword'
)
mail=Mail(app)
# list of topics by {TOPIC:["TITLE", "URL"]}
TOPIC_DICT=Content()
classUser:
defusername(self):
try:
returnstr(session['username'])
except:
return("guest")
user=User()
defuserinformation():
try:
client_name= (session['username'])
guest=False
except:
guest=True
client_name="Guest"
ifnotguest:
try:
c,conn=connection()
c.execute("SELECT * FROM users WHERE username = (%s)",
(thwart(client_name)))
data=c.fetchone()
settings=data[4]
tracking=data[5]
rank=data[6]
exceptException, e:
pass
else:
settings= [0,0]
tracking= [0,0]
rank= [0,0]
returnclient_name, settings, tracking, rank
defupdate_user_tracking():
try:
completed=str(request.args['completed'])
ifcompletedinstr(TOPIC_DICT.values()):
client_name, settings, tracking, rank=userinformation()
iftracking==None:
tracking=completed
else:
ifcompletednotintracking:
tracking=tracking+","+completed
c,conn=connection()
c.execute("UPDATE users SET tracking = %s WHERE username = %s",
(thwart(tracking),thwart(client_name)))
conn.commit()
c.close()
conn.close()
client_name, settings, tracking, rank=userinformation()
else:
pass
exceptException, e:
pass
#flash(str(e))
classRegistrationForm(Form):
username=TextField('Username', [validators.Length(min=4, max=20)])
email=TextField('Email Address', [validators.Length(min=6, max=50)])
password=PasswordField('New Password', [
validators.Required(),
validators.EqualTo('confirm', message='Passwords must match')
])
confirm=PasswordField('Repeat Password')
accept_tos=BooleanField('I accept the <a href="/about/tos" target="blank">Terms of Service</a> and <a href="/about/privacy-policy" target="blank">Privacy Notice</a> (updated Jan 22, 2015)', [validators.Required()])
## LIVE VERSION ####
@app.route('/robots.txt/')
defrobots():
return("User-agent: *\nDisallow: /register/\nDisallow: /login/\nDisallow: /donation-success/")
@app.route('/return-files/')
defreturn_files_tut():
try:
returnsend_file('/var/www/PythonProgramming/PythonProgramming/static/images/python.jpg', attachment_filename='python.jpg')
#return send_file('/var/www/PythonProgramming/PythonProgramming/static/ohhey.pdf', attachment_filename='ohhey.pdf')
exceptExceptionase:
returnstr(e)
@app.route('/file-downloads/')
deffile_downloads():
try:
returnrender_template('downloads.html')
exceptExceptionase:
returnstr(e)
###### DEV VERSION #####
##@app.route('/robots.txt/')
##def robots():
## return("User-agent: *\nDisallow: /")
##
@app.route('/sitemap.xml', methods=['GET'])
defsitemap():
try:
"""Generate sitemap.xml. Makes a list of urls and date modified."""
pages=[]
ten_days_ago=(datetime.now() -timedelta(days=7)).date().isoformat()
# static pages
forruleinapp.url_map.iter_rules():
if"GET"inrule.methodsandlen(rule.arguments)==0:
pages.append(
["http://pythonprogramming.net"+str(rule.rule),ten_days_ago]
)
sitemap_xml=render_template('sitemap_template.xml', pages=pages)
response=make_response(sitemap_xml)
response.headers["Content-Type"] ="application/xml"
returnresponse
exceptExceptionase:
return(str(e))
defindex(chartID='chart_ID', chart_type='bar', chart_height=350):
chart= {"renderTo": chartID, "type": chart_type, "height": chart_height,}
series= [{"name": 'Label1', "data": [1,2,3]}, {"name": 'Label2', "data": [4, 5, 6]}]
title= {"text": 'My Title'}
xAxis= {"categories": ['xAxis Data1', 'xAxis Data2', 'xAxis Data3']}
yAxis= {"title": {"text": 'yAxis Label'}}
returnrender_template('index.html', chartID=chartID, chart=chart, series=series, title=title, xAxis=xAxis, yAxis=yAxis)
@app.route('/', methods=['GET', 'POST'])
defmain():
form=RegistrationForm(request.form)
try:
c,conn=connection()
error=None
ifrequest.method=='POST':
try:
data=c.execute("SELECT * FROM users WHERE username = (%s)",
thwart(request.form['username']))
data=c.fetchone()[2]
ifsha256_crypt.verify(request.form['password'], data):
session['logged_in'] =True
session['username'] =request.form['username']
flash('You are now logged in.')
returnredirect(url_for('dashboard'))
exceptException, e:
flash("What are you doing?")
try:
ifrequest.method=='POST'andform.validate():
username=form.username.data
email=form.email.data
password=sha256_crypt.encrypt((str(form.password.data)))
c,conn=connection()
x=c.execute("SELECT * FROM users WHERE username = (%s)",
(thwart(username)))
ifint(x) >0:
flash("That username is already taken, please choose another")
returnrender_template('register.html', form=form)
else:
c.execute("INSERT INTO users (username, password, email) VALUES (%s, %s, %s)",
(thwart(username), thwart(password), thwart(email)))
conn.commit()
flash('Thanks for registering')
c.close()
conn.close()
gc.collect()
session['logged_in'] =True
session['username'] =username
returnredirect(url_for('dashboard'))
exceptExceptionase:
return(str(e))
else:
flash('Invalid credentials. Try again')
gc.collect()
returnrender_template("main.html", error=error, form=form, page_type="main")
exceptException, e:
return(str(e))
@app.route('/jinjaman/')
defjinjaman():
try:
gc.collect()
data= [15, '15', 'Python is good','Python, Java, php, SQL, C++','<p><strong>Hey there!</strong></p>']
returnrender_template("jinja-templating.html", data=data)
exceptException, e:
return(str(e))
@app.route('/include_example/')
definclude_example():
try:
replies= {'Jack':'Cool post',
'Jane':'+1',
'Erika':'Most definitely',
'Bob':'wow',
'Carl':'amazing!',}
returnrender_template("includes_tutorial.html", replies=replies)
exceptException, e:
return(str(e))
@app.route('/header.py')
defheaderpython():
try:
gc.collect()
returnrender_template("header.py")
exceptException, e:
return(str(e))
@app.errorhandler(404)
defpage_not_found(e):
try:
gc.collect()
rule=request.path
if"feed"inruleor"favicon"inruleor"wp-content"inruleor"wp-login"inruleor"wp-login"inruleor"wp-admin"inruleor"xmlrpc"inruleor"tag"inruleor"wp-include"inruleor"style"inruleor"apple-touch"inruleor"genericons"inruleor"topics"inruleor"category"inruleor"index"inruleor"include"inruleor"trackback"inruleor"download"inruleor"viewtopic"inruleor"browserconfig"inrule:
pass
else:
pass
#flash(str(rule))
returnrender_template('404.html'), 404
exceptExceptionase:
return(str(e))
@app.errorhandler(500)
defpage_not_found(e):
return ("Ouch, looks like we're knocked out"), 500
# login required decorator
deflogin_required(f):
@wraps(f)
defwrap(*args, **kwargs):
if'logged_in'insession:
returnf(*args, **kwargs)
else:
flash('You need to login first.')
returnredirect(url_for('login'))
returnwrap
@app.route('/user/change-password/', methods=['GET', 'POST'])
@login_required
defchange_password():
try:
c,conn=connection()
error=None
ifrequest.method=='POST':
data=c.execute("SELECT * FROM users WHERE username = (%s)",
thwart(user.username()))
data=c.fetchone()[2]
ifsha256_crypt.verify(request.form['password'], data):
flash('Authentication Successful.')
iflen(request.form['npassword']) >0:
#flash("You wanted to change password")
ifrequest.form['npassword'] ==request.form['rnpassword'] andlen(request.form['npassword']) >0:
try:
#flash("new passwords matched")
password=sha256_crypt.encrypt((str(request.form['npassword'])))
c,conn=connection()
data=c.execute("UPDATE users SET password = %s where username = %s",
(password,thwart(user.username())))
conn.commit()
c.close()
conn.close()
flash("Password changed")
exceptException, e:
return(str(e))
else:
flash("Passwords do not match!")
returnrender_template('change-password.html', name=user.username(), error=error)
else:
flash('Invalid credentials. Try again')
error='Invalid credentials. Try again'
gc.collect()
returnrender_template('change-password.html', name=user.username())#, error=error)
exceptException, e:
return(str(e))
@app.route('/login/', methods=['GET','POST'])
deflogin():
try:
c,conn=connection()
error=None
ifrequest.method=='POST':
data=c.execute("SELECT * FROM users WHERE username = (%s)",
thwart(request.form['username']))
data=c.fetchone()[2]
ifsha256_crypt.verify(request.form['password'], data):
session['logged_in'] =True
session['username'] =request.form['username']
#flash('You are now logged in.'+str(session['username']))
returnredirect(url_for('dashboard'))
else:
error='Invalid credentials. Try again'
gc.collect()
returnrender_template('login.html', error=error)
exceptException, e:
error='Invalid credentials. Try again'
returnrender_template('login.html', error=error)
@app.route('/logout/')
deflogout():
session.pop('logged_in', None)
session.clear()
flash('You have been logged out.')
gc.collect()
returnredirect(url_for('main'))
@app.route('/register/', methods=['GET', 'POST'])
defregister():
try:
form=RegistrationForm(request.form)
ifrequest.method=='POST'andform.validate():
#flash("register attempted")
username=form.username.data
email=form.email.data
password=sha256_crypt.encrypt((str(form.password.data)))
c,conn=connection()
x=c.execute("SELECT * FROM users WHERE username = (%s)",
(thwart(username)))
ifint(x) >0:
flash("That username is already taken, please choose another")
returnrender_template('register.html', form=form)
else:
c.execute("INSERT INTO users (username, password, email, tracking) VALUES (%s, %s, %s, %s)",
(thwart(username), thwart(password), thwart(email), thwart("/introduction-to-python-programming/")))
conn.commit()
flash('Thanks for registering')
c.close()
conn.close()
gc.collect()
session['logged_in'] =True
session['username'] =username
returnredirect(url_for('intro_to_py'))
gc.collect()
#flash("hi there.")
returnrender_template('register.html', form=form)
exceptExceptionase:
return(str(e))
deftopic_completion_percent():
try:
client_name, settings, tracking, rank=userinformation()
try:
tracking=tracking.split(",")
except:
pass
iftracking==None:
tracking= []
#flash("tracking is none")
completed_percentages= {}
foreach_topicinTOPIC_DICT:
total=0
total_complete=0
foreachinTOPIC_DICT[each_topic]:
total+=1
fordoneintracking:
ifdone==each[1]:
total_complete+=1
percent_complete=int(((total_complete*100)/total))
completed_percentages[each_topic] =percent_complete
returncompleted_percentages
except:
foreach_topicinTOPIC_DICT:
total=0
total_complete=0
completed_percentages[each_topic] =0.0
returncompleted_percentages
pass
#return basics,pygame,pyopengl,kivy,flask,django,mysql,sqlite,datamanip,dataviz,nltk,svm,clustering,imagerec,forexalgo,robotics,supercomp,tkinter
@app.route('/guided-tutorials/', methods=['GET', 'POST'])
@app.route('/topics/', methods=['GET', 'POST'])
@app.route('/begin/', methods=['GET', 'POST'])
@app.route('/python-programming-tutorials/', methods=['GET', 'POST'])
@app.route('/dashboard/', methods=['GET', 'POST'])
#@login_required
defdashboard():
try:
try:
client_name, settings, tracking, rank=userinformation()
iflen(tracking) <10:
tracking="/introduction-to-python-programming/"
gc.collect()
ifclient_name=="Guest":
flash("Welcome Guest, feel free to browse content. Progress tracking is only available for Logged-in users.")
tracking= ['None']
update_user_tracking()
completed_percentages=topic_completion_percent()
returnrender_template("dashboard.html",topics=TOPIC_DICT, tracking=tracking, completed_percentages=completed_percentages)
exceptException, e:
return((str(e), "please report errors to hskinsley@gmail.com"))
exceptException, e:
return((str(e), "please report errors to hskinsley@gmail.com"))
if__name__=="__main__":
app.run()