-
Notifications
You must be signed in to change notification settings - Fork 38
/
app.py
184 lines (158 loc) · 4.92 KB
/
app.py
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
from flask import (Flask, g, render_template, flash, redirect, url_for,abort)
from flask_bcrypt import check_password_hash
from flask_login import (LoginManager, login_user, logout_user,
login_required, current_user)
import forms
import models
DEBUG = True
PORT = 8000
HOST = '0.0.0.0'
app = Flask(__name__)
app.secret_key = 'asdnafnj#46sjsnvd(*$43sfjkndkjvnskb6441531@#$$6sddf'
"""here secret_key is a random string of alphanumerics"""
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
@login_manager.user_loader
def load_user(userid):
try:
return models.User.get(models.User.id == userid)
except models.DoesNotExist:
return None
@app.before_request
def before_request():
"""Connect to database before each request
g is a global object, passed around all time in flask, used to setup things which
we wanna have available everywhere.
"""
g.db = models.DATABASE
g.db.connect()
g.user = current_user
@app.after_request
def after_request(response):
"""close all database connection after each request"""
g.db.close()
return response
@app.route('/register', methods = ('GET','POST'))
def register():
form = forms.RegisterForm()
if form.validate_on_submit():
flash("Congrats, Registered Successfully!", "success")
models.User.create_user(
username = form.username.data,
email = form.email.data,
password = form.password.data
)
return redirect(url_for('index'))
return render_template('register.html', form = form)
@app.route('/login', methods = ('GET', 'POST'))
def login():
form = forms.LoginForm()
if form.validate_on_submit():
try:
user = models.User.get(models.User.email == form.email.data)
except models.DoesNotExist:
flash("Your email or password does not match", "error")
else:
if check_password_hash(user.password, form.password.data):
login_user(user)
"""Creating a session on user's browser"""
flash("You have been logged in", "success")
return redirect(url_for('index'))
else:
flash("Your email or password does not match", "error")
return render_template('login.html', form = form)
@app.route('/logout')
@login_required
def logout():
logout_user()
flash("You have been logged out.")
return redirect(url_for('login'))
@app.route('/new_post', methods = ('GET', 'POST'))
@login_required
def post():
form = forms.PostForm()
if form.validate_on_submit():
models.Post.create(user = g.user.id,
content = form.content.data.strip())
flash("Message Posted: Thanks!", "success")
return redirect(url_for('index'))
return render_template('post.html', form = form)
@app.route('/')
def index():
stream = models.Post.select().limit(100)
return render_template('stream.html', stream = stream)
@app.route('/stream')
@app.route('/stream/<username>')
def stream(username = None):
template = 'stream.html'
if username and (current_user.is_anonymous or username != current_user.username):
try:
user = models.User.select().where(models.User.username**username).get()
except models.DoesNotExist:
abort(404)
else:
stream = user.posts.limit(100)
else:
stream = current_user.get_stream().limit(100)
user = current_user
if username:
template = 'user_stream.html'
return render_template(template, stream = stream, user = user)
@app.route('/post/<int:post_id>')
def view_post(post_id):
posts = models.Post.select().where(models.Post.id == post_id)
if posts.count() == 0:
abort(404)
return render_template('stream.html', stream = posts)
@app.route('/follow/<username>')
@login_required
def follow(username):
try:
to_user = models.User.get(models.User.username**username)
except models.DoesNotExist:
abort(404)
else:
try:
models.Relationship.create(
from_user = g.user._get_current_object(),
to_user = to_user
)
except models.IntegrityError:
pass
else:
flash("You are now following {}".format(to_user.username), "success")
return redirect(url_for('stream', username=to_user.username))
@app.route('/unfollow/<username>')
@login_required
def unfollow(username):
try:
to_user = models.User.get(models.User.username**username)
except models.DoesNotExist:
abort(404)
else:
try:
models.Relationship.get(
from_user = g.user._get_current_object(),
to_user = to_user
).delete_instance()
except models.IntegrityError:
pass
else:
flash("You have unfollowed {}".format(to_user.username), "success")
return redirect(url_for('stream', username=to_user.username))
@app.errorhandler(404)
def not_found(error):
return render_template('404.html'), 404
if __name__ == '__main__':
models.initialize()
try:
models.User.create_user(
username = 'niteshsharma',
email = '[email protected]',
password = 'password',
admin = True
)
except ValueError:
pass
app.run(debug=DEBUG,host = HOST, port = PORT)