Adding Single Movie CRUD Functionality

#controllers/dashboard/movie.py
import config, copy, lib, datetime, uuid
from flask import render_template, session, request, redirect
from models.userdb import Userdb
from models.moviedb import Moviedb

class Movie():
  def __init__(self):
    self.userdb = Userdb()
    self.lib = lib.Lib()
    self.moviedb = Moviedb()

  def get_post(self):
    vdict = copy.deepcopy(config.vdict)
    vdict['site_title'] = "ទំព័រ​ភាពយន្តទោល"
    vdict['datetime'] = self.lib.get_timezone()
    session['page'] = 0

    if (request.method == "POST") and ('logged-in' in session):
      vid = request.form['fvid']
      type = request.form['ftype']
      title = request.form['ftitle']
      content = request.form['fcontent']
      country = request.form['fcountry']
      date = request.form['fdate']
      time = request.form['ftime']
      author = session['logged-in']

      try:
        date = datetime.datetime.strptime(date, "%d/%m/%Y")
      except ValueError:
        vdict['message'] = 'ទំរង់​កាលបរិច្ឆេទ​មិន​ត្រឹមត្រូវ!'
        return render_template('dashboard/movie.html', data=vdict)

      try:
        time = datetime.datetime.strptime(time, "%H:%M:%S")
      except ValueError:
        vdict['message'] = 'ទំរង់​ពេល​វេលា​មិន​ត្រឹមត្រូវ!'
        return render_template('dashboard/movie.html', data=vdict)

      if 'edit-id' in session:
        id = session['edit-id']
        self.moviedb.update(vid, type, title, country, content, date, time, author, id)
        session.pop('edit-id', None)
      else:
        id = str(uuid.uuid4().int)
        self.moviedb.insert(id, vid, type, title, country, content, date, time, author)

      vdict['movies'] = self.moviedb.select(vdict['dashboard_max_post'])
      vdict['thumbs'] = self.lib.get_thumbs(vdict['movies'], 5, type='movie')
      return render_template('dashboard/movie.html', data=vdict)

    elif 'logged-in' in session:
      vdict['movies'] = self.moviedb.select(vdict['dashboard_max_post'])
      vdict['thumbs'] = self.lib.get_thumbs(vdict['movies'], 5, type='movie')
      return render_template('dashboard/movie.html', data=vdict)
    else:
      return redirect('/login/')

  def edit(self, id):
    vdict = copy.deepcopy(config.vdict)
    vdict['site_title'] = 'កែតំរូវ​ភាពយន្ត​ទោល'
    session['edit-id'] = id

    if 'logged-in' in session:
      vdict['movies'] = self.moviedb.select(vdict['dashboard_max_post'])
      vdict['thumbs'] = self.lib.get_thumbs(vdict['movies'], 5, type='movie')
      vdict['movie'] = self.moviedb.select(id=id)
      date = (vdict['movie'][6]).strftime('%d/%m/%Y')
      time = (vdict['movie'][7]).strftime('%H:%M:%S')
      vdict['datetime'] = (date, time)

      return render_template('dashboard/movie.html', data=vdict)

    return redirect('/login/')

  def delete(self, id):
    self.moviedb.delete(id)
    return redirect('/dashboard/movie/')

  def load(self):
    if 'logged-in' in session:
      vdict = copy.deepcopy(config.vdict)
      session['page'] += 1
      vdict['movies'] = self.moviedb.select(vdict['dashboard_max_post'], page=session['page'])
      vdict['thumbs'] = self.lib.get_thumbs(vdict['movies'], 5, type="movie")

      new_list = []
      for movie in vdict['movies']:
        new_movie = list(movie)
        new_movie[6] = movie[6].strftime('%d/%m/%Y') 
        new_movie[7] = movie[7].strftime('%H:%M:%S') 
        new_list.append(new_movie)

      vdict['movies'] = new_list
      return vdict
    else:
      return render_template('login.html', data=vdict)
#models/userdb.py
import os, psycopg2

class Moviedb():
  def __init__(self):
    self.create_table()

  def set_conection(self):
    if 'DYNO' in os.environ:
      DATABASE_URL = os.environ['DATABASE_URL']
      self.conn = psycopg2.connect(DATABASE_URL, sslmode='require')
      self.cursor = self.conn.cursor()
    else: 
      self.conn = psycopg2.connect(
        database="postgres", 
        user="postgres", 
        password="sokhavuth", 
        host="localhost", 
        port="5432"
      )

      self.cursor = self.conn.cursor()

  def create_table(self):
    self.set_conection()
    
    SQL = '''CREATE TABLE IF NOT EXISTS MOVIES(
      ID TEXT,
      VID TEXT,
      TYPE TEXT,
      TITLE TEXT,
      COUNTRY TEXT,
      CONTENT TEXT,
      CDATE DATE,
      CTIME TIME,
      AUTHOR TEXT
    )'''

    self.cursor.execute(SQL)
    self.conn.commit()
    self.conn.close() 

  def insert(self, *movie):
    self.set_conection()

    self.cursor.execute("INSERT INTO MOVIES (ID, VID, TYPE, TITLE, COUNTRY, CONTENT, CDATE, CTIME, AUTHOR) VALUES %s ", (movie,))
  
    self.conn.commit()
    self.conn.close()

  def select(self, amount=5, id='', page=0):
    self.set_conection()

    if id:
      SQL = "SELECT * FROM MOVIES WHERE ID=%s"
      self.cursor.execute(SQL, (id,))
      result = self.cursor.fetchone()
    elif page:
      SQL = "SELECT * FROM MOVIES ORDER BY CDATE DESC, CTIME DESC OFFSET %s ROWS FETCH NEXT %s ROWS ONLY"
      self.cursor.execute(SQL, (amount*page, amount))
      result = self.cursor.fetchall()
    else:
      SQL = "SELECT * FROM MOVIES ORDER BY CDATE DESC, CTIME DESC LIMIT %s"
      self.cursor.execute(SQL, (amount,))
      result = self.cursor.fetchall()

    self.conn.close()
    return result

  def delete(self, id):
    self.set_conection()

    SQL = "DELETE FROM MOVIES WHERE ID = %s"
    self.cursor.execute(SQL, (id,))

    self.conn.commit()
    self.conn.close()

  def update(self, *movie):
    self.set_conection()

    sql = "UPDATE MOVIES SET VID = %s, TYPE = %s, TITLE = %s, COUNTRY = %s, CONTENT = %s, CDATE = %s, CTIME = %s, AUTHOR = %s WHERE ID = %s"
    self.cursor.execute(sql, movie)

    self.conn.commit()
    self.conn.close()

  def search(self, query):
    self.set_conection()
  
    sql = "SELECT * from USERS WHERE"
    sql += " EMAIL LIKE '%"+query+"%'"
    sql += " OR CONTENT LIKE '%"+query+"%'"
    sql += " ORDER BY CATDATE DESC, CATTIME DESC LIMIT 20"

    self.cursor.execute(sql)
    
    result = self.cursor.fetchall()
    return result
<!--templates/dashboard/movie.html-->
{% extends 'dashboard/index.html' %}
  
{% block head %}
{{ super() }}
<link href="/static/styles/dashboard/movie.css" rel="stylesheet">
<script src="/static/scripts/dashboard/movie.js"></script>
{% endblock %}

{% block content %}
  <form id='movie' action='/dashboard/movie/' method="POST" >
    {% if 'movie' in data %}
    <input id='movie-title' value="{{ data['movie'][3] }}" name="ftitle" type="text" placeholder="ចំណង​ជើងភាពយន្ត" required />
    <textarea name="fcontent" id="editor" >{{ data['movie'][5] }}</textarea>
    {% else: %}
    <input id='movie-title' value="" name="ftitle" type="text" placeholder="ចំណង​ជើង​ភាពយន្ត" required />
    <textarea name="fcontent" id="editor" ></textarea>
    {% endif %}
    <div id="bottombar">
      <input id="submit" class="bottom-widget" type="submit" value="ចុះ​ផ្សាយ">
      {% if 'movie' in data %}
      <input type="text" value="{{ data['movie'][1] }}" class="bottom-widget" name="fvid" required />
      <select id="type" class="bottom-widget" name="ftype">
        <option>YouTube</option>
        <option>Facebook</option>
        <option>Dailymotion</option>
        <option>Vimeo</option>
        <option>OKRU</option>
      </select>
      <script>$("#type").val("{{data['movie'][2]}}").change();</script>
      <select id="country" class="bottom-widget" name="fcountry" >
        <option>World</option>
        <option>Korean</option>
        <option>Chinese</option>
        <option>Thai</option>
        <option>Khmer</option>
      </select>
      <script>$("#country").val("{{data['movie'][4]}}").change();</script>
      <input id="movie-date" value="{{ data['datetime'][0] }}" class="bottom-widget " type="text" name="fdate" required />
      <input id="movie-time" value="{{ data['datetime'][1] }}" class="bottom-widget " type="text" name="ftime" required />
      {% else %}
      <input type="text" value="" class="bottom-widget" placeholder="Video ID" name="fvid" required />
      <select id="type" class="bottom-widget" name="ftype">
        <option>YouTube</option>
        <option>Facebook</option>
        <option>Dailymotion</option>
        <option>Vimeo</option>
        <option>OKRU</option>
      </select>
      <select id="country" class="bottom-widget" name="fcountry" >
        <option>World</option>
        <option>Korean</option>
        <option>Chinese</option>
        <option>Thai</option>
        <option>Khmer</option>
      </select>
      <input id="user-date" value="{{ data['datetime'][0] }}" class="bottom-widget user-date" type="text" name="fdate" required />
      <input id="user-time" value="{{ data['datetime'][1] }}" class="bottom-widget user-time" type="text" name="ftime" required />
      {% endif %}
    </div>
  </form>
  <div id="message">{{ data['message'] }}</div>
  <script src="/static/scripts/ckeditor/config.js"></script>
{% endblock %}
  
{% block item_listing %}
    <ul id="item-listing" class="item-listing region">
      {% if 'movies' in data %}
      {% for v in range(data['movies']|length) %}
      <li class="movie">
        <a class="thumbnail" href="/movie/{{ data['movies'][v][0] }}">
          <img src="{{data['thumbs'][v]}}" />
        </a>
        <div class='title'>
          <a href="/movie/{{ data['movies'][v][0] }}">{{ data['movies'][v][3] }}</a>
          <div>{{ data['movies'][v][4] }}</div>
          <span>{{ data['movies'][v][6].strftime('%d/%m/%Y') }}</span>
        </div>
        <div class="crud">
          <div class="user">{{ data['movies'][v][8] }}</div>
          <a href='/dashboard/movie/edit/{{ data["movies"][v][0] }}'><img src="/static/images/edit.png" /></a>
          <a href='/dashboard/movie/delete/{{ data["movies"][v][0] }}'><img src="/static/images/delete.png" /></a>
        </div>
      </li>
      {% endfor %}
      {% endif %}
    </ul>
    <div id="load-more" class="load-more region">
      <img onclick="movie.load_items('/dashboard/movie/load/', 'movies')" src="/static/images/load-more.png" />
    </div>
{% endblock %}
//static/scritps/dashboard/movie.js
class Movie{
  load_items(url){
    $('#load-more img').attr('src', '/static/images/loading.gif');
    $.get(url, function(data, status){
      if(status === "success"){
        movie.listing_movies(data)
      }else{
        alert('Fail to connect to server.');
      }
    });
  }
  listing_movies(data){
    var html = '';
    for(var v=0; v<data['movies'].length; v++){
      html += '<li class="movie">';
      html += `<a class="thumbnail" href="/movie/${ data['movies'][v][0] }"><img src="${data['thumbs'][v]}" /></a>`;
      html += `<div class='title'>`;
      html += `<a href="/movie/${ data['movies'][v][0] }">${ data['movies'][v][3] }</a>`;
      html += `<div>${ data['movies'][v][4] }</div>`
      html += `<span>${ data['movies'][v][6] }</span>`;
      html += `</div>`;
      html += `<div class="crud">`;
      html += `<div class="user">${ data['movies'][v][8] }</div>`;
      html += `<a href='/dashboard/movie/delete/${ data["movies"][v][0] }'><img src="/static/images/delete.png" /></a>`;
      html += `<a href='/dashboard/movie/edit/${ data["movies"][v][0] }'><img src="/static/images/edit.png" /></a>`;
      html += `</div>`;
      html += `</li>`;
    }
  
    $('#item-listing').append(html);
    $('#load-more img').attr('src', '/static/images/load-more.png')
  }
}//end class

const movie = new Movie();

GitHub: "https://github.com/Sokhavuth/ETV
Heroku: https://khmerweb-etv.herokuapp.com/

Comments

Popular posts from this blog