Making Ajax Call to Load Posts
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
#controllers/post.py
import config, lib, datetime, uuid
from bottle import route, template, request, redirect, response
from models import postdb
 
@route('/post/<id:int>')
def post(id):
  config.kargs['blogTitle'] = "ទំព័រ​ការផ្សាយ"
  config.kargs['post'] = postdb.select(1, id)
  config.kargs['posts'] = postdb.select(config.kargs['frontPagePostLimit'])
  config.kargs['thumbs'] = lib.getPostThumbs(config.kargs['posts'])
  author = request.get_cookie("logged-in", secret=config.kargs['secretKey'])
  if author:
    config.kargs['showEdit'] = True
 
  return template('post', data=config.kargs)
 
@route('/posting', method="POST")
def posting():
  author = request.get_cookie("logged-in", secret=config.kargs['secretKey'])
  if ((author != "Guest") and postdb.check(author)):
    title = request.forms.getunicode('fpost-title')
    if title == "":
      title = "untitled"
 
    postdate = request.forms.getunicode('fpost-date')
    posttime = request.forms.getunicode('fpost-time')
    category = request.forms.getunicode('fcategory')
    content = request.forms.getunicode('fcontent')
 
    try:
      postdate = datetime.datetime.strptime(postdate, "%d-%m-%Y")
    except ValueError:
      config.kargs['message'] = 'ទំរង់​កាលបរិច្ឆេទ​មិន​ត្រឹមត្រូវ!'
      return template('dashboard/home', data=config.kargs)
 
    try:
      datetime.datetime.strptime(posttime, "%H:%M:%S")
    except ValueError:
      config.kargs['message'] = 'ទំរង់​ពេល​វេលា​មិន​ត្រឹមត្រូវ!'
      return template('dashboard/home', data=config.kargs)
 
    if 'postId' in config.kargs:
      id = config.kargs['postId']
      postdb.update(title, postdate, posttime, category, content, id)
      del config.kargs['postId']
    else:
      postdb.insert(str(uuid.uuid4().int), title, author, postdate, posttime, category, content)
   
  redirect('/login')
 
@route('/post/delete/<id:int>')
def delete(id):
  author = request.get_cookie("logged-in", secret=config.kargs['secretKey'])
  if ((author != "Guest") and postdb.check(author)):
    postdb.delete(id)
 
  redirect('/login')
 
@route('/post/edit/<id:int>')
def edit(id):
  author = request.get_cookie("logged-in", secret=config.kargs['secretKey'])
  if ((author != "Guest") and postdb.check(author)):
    config.kargs['post'] = postdb.select(1, id)
    config.kargs['edit'] = True
    config.kargs['postId'] = id
    return template('dashboard/home', data=config.kargs)
   
  redirect('/login')
 
@route('/paginate')
def paginate():
  posts = postdb.select(config.kargs['frontPagePostLimit'], page=config.kargs['page'])
   
  def toString(post):
    post[3] = post[3].strftime('%d-%m-%Y')
    post[4] = post[4].strftime('%H:%M:%S')
 
  if posts:
    config.kargs['page'] += 1
    posts = [list(obj) for obj in posts ]
 
    [toString(obj) for obj in posts]
    thumbs = lib.getPostThumbs(posts)
   
    return {'json':posts, 'thumbs':thumbs}
  else:
    return {'json':0}
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
#models/postdb.py
import os
import psycopg2
 
def createTable():
  if 'DYNO' in os.environ:
    DATABASE_URL = os.environ['DATABASE_URL']
    conn = psycopg2.connect(DATABASE_URL, sslmode='require')
    cursor = conn.cursor()
  else:
    conn = psycopg2.connect(
      database="postgres",
      user="postgres",
      password="sokhavuth",
      host="localhost",
      port="5432"
    )
 
    cursor = conn.cursor()
 
  SQL = '''CREATE TABLE IF NOT EXISTS POST(
  ID TEXT,
  TITLE TEXT,
  AUTHOR TEXT,
  POSTDATE DATE,
  POSTTIME TIME,
  CATEGORY TEXT,
  CONTENT TEXT
  )'''
 
  cursor.execute(SQL)
   
  conn.commit()
  conn.close()
 
def insert(*post):
  createTable()
  if 'DYNO' in os.environ:
    DATABASE_URL = os.environ['DATABASE_URL']
    conn = psycopg2.connect(DATABASE_URL, sslmode='require')
    cursor = conn.cursor()
  else:
    conn = psycopg2.connect(
      database="postgres",
      user="postgres",
      password="sokhavuth",
      host="localhost",
      port="5432"
    )
 
    cursor = conn.cursor()
 
  cursor.execute("INSERT INTO POST (ID, TITLE, AUTHOR, POSTDATE, POSTTIME, CATEGORY, CONTENT) VALUES %s ", (post,))
   
  conn.commit()
  conn.close()
 
def select(amount, id=None, page=0):
  createTable()
 
  if 'DYNO' in os.environ:
    DATABASE_URL = os.environ['DATABASE_URL']
    conn = psycopg2.connect(DATABASE_URL, sslmode='require')
    cursor = conn.cursor()
  else:
    conn = psycopg2.connect(
      database="postgres",
      user="postgres",
      password="sokhavuth",
      host="localhost",
      port="5432"
    )
 
    cursor = conn.cursor()
  if id and (amount == 1):
    cursor.execute("SELECT * FROM POST WHERE ID = '" + str(id) +"'")
  elif page:
    SQL = "SELECT * FROM POST ORDER BY POSTDATE DESC, POSTTIME DESC OFFSET %s ROWS FETCH NEXT %s ROWS ONLY"
    cursor.execute(SQL, (amount*page, amount))
  else:
    cursor.execute("SELECT * FROM POST ORDER BY POSTDATE DESC, POSTTIME DESC LIMIT " + str(amount))
     
  result = cursor.fetchall()
  return result
 
def check(username):
  if 'DYNO' in os.environ:
    DATABASE_URL = os.environ['DATABASE_URL']
    conn = psycopg2.connect(DATABASE_URL, sslmode='require')
    cursor = conn.cursor()
  else:
    conn = psycopg2.connect(
      database="postgres",
      user="postgres",
      password="sokhavuth",
      host="localhost",
      port="5432"
    )
 
    cursor = conn.cursor()
 
  cursor.execute("SELECT USERNAME FROM USERS WHERE USERNAME = '"+ username + "' LIMIT 1")
  result = cursor.fetchone()
  if result:
    return True
  else:
    return False
 
def delete(id):
  if 'DYNO' in os.environ:
    DATABASE_URL = os.environ['DATABASE_URL']
    conn = psycopg2.connect(DATABASE_URL, sslmode='require')
    cursor = conn.cursor()
  else:
    conn = psycopg2.connect(
      database="postgres",
      user="postgres",
      password="sokhavuth",
      host="localhost",
      port="5432"
    )
 
    cursor = conn.cursor()
 
  cursor.execute("DELETE FROM POST WHERE ID = '" + str(id) + "'")
 
  conn.commit()
  conn.close()
 
def update(*args):
  if 'DYNO' in os.environ:
    DATABASE_URL = os.environ['DATABASE_URL']
    conn = psycopg2.connect(DATABASE_URL, sslmode='require')
    cursor = conn.cursor()
  else:
    conn = psycopg2.connect(
      database="postgres",
      user="postgres",
      password="sokhavuth",
      host="localhost",
      port="5432"
    )
 
    cursor = conn.cursor()
 
  sql = "UPDATE POST SET TITLE = %s, POSTDATE = %s, POSTTIME = %s, CATEGORY = %s, CONTENT = %s WHERE ID = '%s' "
   
  cursor.execute(sql, args)
   
  conn.commit()
  conn.close()
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
<!--views/dashboard/footer.tpl-->
      <footer class="footer region">
        <div class="post-panel">
        %if 'posts' in data:
          %for v in range(len(data['posts'])):
            <div class="post-outer">
              <a class="post-thumb" href="/post/{{data['posts'][v][0]}}"><img src="{{data['thumbs'][v]}}" /></a>
                <a class="post-title" href="/post/{{data['posts'][v][0]}}">{{data['posts'][v][1]}}</a>
                %postdate = data['posts'][v][3].strftime("%d-%m-%Y")
                <div class="post-date">{{postdate}}</div>
            </div>
          %end
        %end
        </div>
        <div id="pagination">
          <img onclick="paginate()" src="/static/images/load-more.png" />
        </div>
        <script>
          function paginate(){
            $.get("/paginate", function(data, status){
              if(status && data.json){
                var posts = data.json;
                var thumbs = data.thumbs;
                var html = '';
 
                $('#pagination img').attr('src', '/static/images/loading.gif');
 
                for(var index in posts){
                  html += '<div class="post-outer">';
                  html += `<a class="post-thumb" href="/post/${posts[index][0]}"><img src="${thumbs[index]}" /></a>`;
                  html += `<a class="post-title" href="/post/${posts[index][0]}">${posts[index][1]}</a>`;
                  html += `<div class="post-date">${posts[index][3]}</div>`;
                  html += '</div>';
                }
 
                $('.post-panel').append(html);
                $('#pagination img').attr('src', '/static/images/load-more.png');
 
                var width = $('footer .post-thumb img').css('width');
                var height = parseInt(width) / 16 * 9;
                $('footer .post-thumb').css({'height':height});
              }
            });
          }
 
          var width = $('footer .post-thumb img').css('width');
          var height = parseInt(width) / 16 * 9;
          $('footer .post-thumb').css({'height':height});
 
          $(window).resize(function(){
            var width = $('footer .post-thumb img').css('width');
            var height = parseInt(width) / 16 * 9;
            $('footer .post-thumb').css({'height':height});
          });
        </script>
      </footer>
    </div><!--site-->
  </body>
</html>

GitHub: https://github.com/Sokhavuth/kwblog
Heroku: https://khmerweb-kwblog.herokuapp.com/