Skip to content

Commit

Permalink
Migration python3
Browse files Browse the repository at this point in the history
Fixes: #114
  • Loading branch information
ptitoliv committed Mar 22, 2021
1 parent b98304e commit cc2cd40
Show file tree
Hide file tree
Showing 20 changed files with 385 additions and 325 deletions.
24 changes: 13 additions & 11 deletions cineapp/__init__.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
# -*- coding: utf-8 -*-

from werkzeug.contrib.fixers import ProxyFix
from __future__ import print_function
from werkzeug.middleware.proxy_fix import ProxyFix
from flask import Flask
from flask.ext.login import login_user, logout_user, current_user, login_required, LoginManager
from flask.ext.sqlalchemy import SQLAlchemy
from flask_login import login_user, logout_user, current_user, login_required, LoginManager
from flask_sqlalchemy import SQLAlchemy
from flask import Flask, session
from flask.ext.session import Session
from flask.ext.mail import Mail
from flask.ext.babel import Babel
from flask_session import Session
from flask_mail import Mail
from flask_babel import Babel
import logging, sys, os
from logging.handlers import RotatingFileHandler
from flask_socketio import SocketIO
from flask_msearch import Search

app = Flask(__name__)

Expand Down Expand Up @@ -39,10 +41,10 @@
app.config['MAX_CONTENT_LENGTH'] = 1 * 1024 * 1024

# Initialize path with default values if necessary
if not app.config.has_key('AVATARS_URL'):
if 'AVATARS_URL' not in app.config:
app.config['AVATARS_URL'] = "/static/avatars/"

if not app.config.has_key('POSTERS_URL'):
if 'POSTERS_URL' not in app.config:
app.config['POSTERS_URL'] = "/static/posters/"

# TMVDB parameters
Expand All @@ -55,7 +57,7 @@
app.config.from_pyfile(os.path.join(app.root_path,'../configs/settings.cfg'))

# Check if API_KEY is defined
if not app.config.has_key('API_KEY'):
if 'API_KEY' not in app.config:
# Let's import it from environnment
if os.environ.get('API_KEY') != None:
app.config['API_KEY'] = os.environ.get('API_KEY')
Expand Down Expand Up @@ -93,15 +95,15 @@
if not os.path.isdir(app.config['LOGDIR']):
os.makedirs(app.config['LOGDIR'],0o755)
except:
print "Unable to create " + app.config['LOGDIR']
print("Unable to create " + app.config['LOGDIR'])
sys.exit(2)

# Create the avatar directory if it doesn't exists
try:
if not os.path.isdir(app.config['AVATARS_FOLDER']):
os.makedirs(app.config['AVATARS_FOLDER'],0o755)
except:
print "Unable to create " + app.config['AVATARS_FOLDER']
print("Unable to create " + app.config['AVATARS_FOLDER'])
sys.exit(2)

# Open a file rotated every 100MB
Expand Down
16 changes: 8 additions & 8 deletions cineapp/auth.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
# -*- coding: utf-8 -*-

from functools import wraps
from flask.ext.login import current_user
from flask_login import current_user
from flask import flash, redirect, url_for

def guest_control(func):
@wraps(func)
def decorated_view(*args, **kwargs):
if current_user.is_guest == True:
flash("Accès interdit pour les invités","danger")
return redirect(url_for('list_movies'))
return func(*args, **kwargs)
return decorated_view
@wraps(func)
def decorated_view(*args, **kwargs):
if current_user.is_guest == True:
flash("Accès interdit pour les invités","danger")
return redirect(url_for('list_movies'))
return func(*args, **kwargs)
return decorated_view
9 changes: 5 additions & 4 deletions cineapp/chat.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
# -*- coding: utf-8 -*-

from __future__ import print_function
from cineapp import app, lm, socketio, db
from flask import render_template, flash, redirect, url_for, g, request, session
from flask.ext.login import login_user, logout_user, current_user, login_required
from flask.ext.socketio import SocketIO, emit
from flask_login import login_user, logout_user, current_user, login_required
from flask_socketio import SocketIO, emit
from cineapp.models import ChatMessage, User
from cineapp.emails import chat_message_notification
from cineapp.push import notification_send
Expand Down Expand Up @@ -58,8 +59,8 @@ def transmit_message(message,notify=False):
if user != None and user.id != logged_user.id:
# We found a user, let's send him a notification who is not ourself
chat_message_notification(message,user)
except Exception,e:
print e
except Exception as e:
print(e)

# Send the message
emit('message', { 'user': message.posted_by.nickname, 'date': message_date_formatted, 'avatar': message.posted_by.avatar, 'msg' : message.message }, broadcast=True)
Expand Down
5 changes: 3 additions & 2 deletions cineapp/comments.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
# -*- coding: utf-8 -*-

from __future__ import absolute_import
from cineapp import app, db, lm
from flask import render_template, flash, redirect, url_for, g, request, session, jsonify
from flask.ext.login import login_required
from flask_login import login_required
from cineapp.models import User, MarkComment
from datetime import datetime
from emails import mark_comment_notification
from .emails import mark_comment_notification
from sqlalchemy.exc import IntegrityError, InvalidRequestError
from sqlalchemy.orm.exc import FlushError

Expand Down
5 changes: 3 additions & 2 deletions cineapp/emails.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# -*- coding: utf-8 -*-

from builtins import str
from flask import render_template,g
from flask.ext.mail import Message
from flask_mail import Message
from cineapp import mail, db
from cineapp.models import User
from threading import Thread
Expand Down Expand Up @@ -49,7 +50,7 @@ def mark_movie_notification(mark,notif_type):

# Convert the HTML content to text in order to have a nice display in the mail
html_converter = html2text.HTML2Text()
mark.comment=html_converter.handle(mark.comment).strip()
mark.comment=html_converter.handle(mark.comment).strip()

for cur_user in users:
# Check if the cur_user is the logged user who added the movie
Expand Down
14 changes: 8 additions & 6 deletions cineapp/favorites.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
# -*- coding: utf-8 -*-

from __future__ import print_function
from __future__ import absolute_import
from cineapp import app, db, lm
from flask import render_template, flash, redirect, url_for, g, request, session, jsonify
from flask.ext.login import login_required
from flask_login import login_required
from cineapp.models import User, FavoriteMovie
from datetime import datetime
from emails import favorite_update_notification
from .emails import favorite_update_notification
from sqlalchemy.exc import IntegrityError, InvalidRequestError
from sqlalchemy.orm.exc import FlushError

Expand Down Expand Up @@ -42,9 +44,9 @@ def set_favorite_movie(movie,user):
app.logger.error("Erreur SQL sur l'ajout du favori")
return jsonify({ "status": "danger", "message": u"Film déja défini comme favori" })

except Exception,e:
except Exception as e:
db.session.rollback()
print e
print(e)
app.logger.error("Erreur générale sur l'ajout du favori")
return jsonify({ "status": "danger", "message": u"Impossible d'ajouter le film en favori" })

Expand Down Expand Up @@ -78,8 +80,8 @@ def delete_favorite_movie(movie,user):
app.logger.error("Erreur SQL sur la suppression du favori")
return jsonify({ "status": "danger", "message": u"Le film n\'est pas enregistré comme un favori" })

except Exception,e:
except Exception as e:
db.session.rollback()
print e
print(e)
app.logger.error("Erreur générale sur la suppression du favori")
return jsonify({ "status": "danger", "message": u"Impossible de supprimer le film en favori" })
18 changes: 9 additions & 9 deletions cineapp/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@

# Define wtforms widget and field
class CKTextAreaWidget(widgets.TextArea):
def __call__(self, field, **kwargs):
kwargs.setdefault('class_', 'ckeditor')
html_string = super(CKTextAreaWidget, self).__call__(field, **kwargs)
html_string += ("""<script>
CKEDITOR.replace( '%s', {
enterMode: CKEDITOR.ENTER_BR
} );
</script>""" % field.id)
return widgets.HTMLString(html_string)
def __call__(self, field, **kwargs):
kwargs.setdefault('class_', 'ckeditor')
html_string = super(CKTextAreaWidget, self).__call__(field, **kwargs)
html_string += ("""<script>
CKEDITOR.replace( '%s', {
enterMode: CKEDITOR.ENTER_BR
} );
</script>""" % field.id)
return widgets.HTMLString(html_string)

class CKTextAreaField(fields.TextAreaField):
widget = CKTextAreaWidget()
Expand Down
7 changes: 4 additions & 3 deletions cineapp/forms.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# -*- coding: utf-8 -*-

from flask.ext.wtf import Form
from flask.ext.wtf.html5 import SearchField
from builtins import object
from flask_wtf import FlaskForm as Form
from wtforms.fields.html5 import SearchField
from wtforms import StringField, PasswordField, RadioField, SubmitField, HiddenField, SelectField, TextAreaField, BooleanField, DateField, FileField
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from wtforms.validators import Required,DataRequired, EqualTo, Email, URL, ValidationError
Expand Down Expand Up @@ -37,7 +38,7 @@ class AddMovieForm(Form):
type = QuerySelectField(query_factory=get_types,get_label='type')

class MarkMovieForm(Form):
class Meta:
class Meta(object):
locales = ('de_DE', 'de')

mark = StringField('Note du Film', [DataRequired()])
Expand Down
6 changes: 4 additions & 2 deletions cineapp/jinja_filters.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import print_function
from past.builtins import basestring
from cineapp import app
import datetime

Expand All @@ -25,6 +27,6 @@ def date_format(date,format_date):
return date_to_convert.strftime(format_date)
else:
return date.strftime(format_date)
except Exception,e:
print e
except Exception as e:
print(e)
return None
3 changes: 2 additions & 1 deletion cineapp/migration_types.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import absolute_import
# cineapp/migration_types.py

from types import JSONEncodedDict
from .types import JSONEncodedDict
45 changes: 24 additions & 21 deletions cineapp/models.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# -*- coding: utf-8 -*-
from builtins import str
from cineapp import app,db
from sqlalchemy import desc,text, DefaultClause, orm
import flask.ext.whooshalchemy as whooshalchemy
from flask_msearch import Search
from whoosh.analysis import CharsetFilter, NgramWordAnalyzer
from whoosh import fields
from whoosh.support.charset import accent_map
Expand Down Expand Up @@ -43,14 +44,14 @@ def is_guest(self):

def get_id(self):
try:
return unicode(self.id) # Python 2
return str(self.id) # Python 2
except NameError:
return str(self.id) # Python 3

def __repr__(self):
return '<User %r>' % (self.nickname)

def __init__(self,guest=False):
def __init__(self,guest=False):
self.notifications={ "notif_own_activity" : None,
"notif_movie_add" : None,
"notif_mark_add": None,
Expand All @@ -68,7 +69,7 @@ def __init__(self,guest=False):


@orm.reconstructor
def init_on_load(self):
def init_on_load(self):
self.guest=False

def serialize(self):
Expand Down Expand Up @@ -108,7 +109,7 @@ class Movie(db.Model):
# Settings for FTS (WooshAlchemy)
__searchable__ = [ 'name', 'director', 'original_name' ]
charmap = charset_table_to_dict(default_charset)
__analyzer__ = NgramWordAnalyzer(3) | CharsetFilter(charmap)
__msearch_analyzer__ = NgramWordAnalyzer(3) | CharsetFilter(charmap)

id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100),index=True)
Expand All @@ -128,7 +129,7 @@ class Movie(db.Model):
def __repr__(self):
return '<Movie %r>' % (self.name)

def next(self):
def __next__(self):
"""
Return the next item into the database
Let's consider alphabetical order
Expand Down Expand Up @@ -174,16 +175,16 @@ class ChatMessage(db.Model):
message = db.Column(db.String(1000))

class MarkComment(db.Model):
__tablename__ = "mark_comment"
__table_args__ = (db.ForeignKeyConstraint([ "mark_user_id", "mark_movie_id" ], [ "marks.user_id", "marks.movie_id" ]), {'mysql_charset': 'utf8', 'mysql_collate': 'utf8_general_ci'} )

markcomment_id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
mark_user_id = db.Column(db.Integer)
mark_movie_id = db.Column(db.Integer)
posted_when = db.Column(db.DateTime())
deleted_when = db.Column(db.DateTime())
message = db.Column(db.String(1000))
__tablename__ = "mark_comment"
__table_args__ = (db.ForeignKeyConstraint([ "mark_user_id", "mark_movie_id" ], [ "marks.user_id", "marks.movie_id" ]), {'mysql_charset': 'utf8', 'mysql_collate': 'utf8_general_ci'} )
markcomment_id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
mark_user_id = db.Column(db.Integer)
mark_movie_id = db.Column(db.Integer)
posted_when = db.Column(db.DateTime())
deleted_when = db.Column(db.DateTime())
message = db.Column(db.String(1000))
user = db.relationship("User", backref="comments")
old_message = None

Expand All @@ -200,14 +201,14 @@ def serialize(self):
class FavoriteMovie(db.Model):
__tablename__ = "favorite_movies"
__table_args__ = {'mysql_charset': 'utf8', 'mysql_collate': 'utf8_general_ci'}

movie_id = db.Column(db.Integer, db.ForeignKey('movies.id'), primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True)
movie = db.relationship('Movie', backref='favorite_users',lazy="joined")
user = db.relationship('User', backref='favorite_movies',foreign_keys='FavoriteMovie.user_id',lazy="joined")
star_type = db.Column(db.String(100),db.ForeignKey('favorite_types.star_type'))
added_when = db.Column(db.DateTime())
deleted_when = db.Column(db.DateTime())
added_when = db.Column(db.DateTime())
deleted_when = db.Column(db.DateTime())

def serialize(self):
return {
Expand Down Expand Up @@ -252,5 +253,7 @@ def serialize(self):
}
}

# Enable FTS indexation
whooshalchemy.whoosh_index(app, Movie)
# FTS Search engine init (Based on Flask-Msearch
#search = Search()
#search.init_app(app)
#search.create_index(Movie, update=True)
21 changes: 11 additions & 10 deletions cineapp/push.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import print_function
from cineapp import app, db, lm
from flask.ext.login import login_required, request
from flask import jsonify, session, g, url_for
from flask_login import login_required
from flask import jsonify, session, g, url_for, request
from pywebpush import webpush, WebPushException
from cineapp.models import PushNotification
import json, traceback, sys, datetime, time
Expand Down Expand Up @@ -43,15 +44,15 @@ def notification_send(text,active_subscriptions):
}
)
except WebPushException as ex:
# If there is an error let's remove the subscription
app.logger.error("Subscription for endpoint %s is incorrect ==> Delete it", cur_active_sub)
print traceback.print_exc(file=sys.stdout);

# Let's remove the notification
notification_unsubscribe(cur_active_sub)
# If there is an error let's remove the subscription
app.logger.error("Subscription for endpoint %s is incorrect ==> Delete it", cur_active_sub)
print(traceback.print_exc(file=sys.stdout));
# Let's remove the notification
notification_unsubscribe(cur_active_sub)

print("I'm sorry, Dave, but I can't do that: {}", repr(ex))
print(ex.response.json())
print(("I'm sorry, Dave, but I can't do that: {}", repr(ex)))
print(ex.response.json())

def notification_unsubscribe(sub):
try:
Expand Down
Loading

0 comments on commit cc2cd40

Please sign in to comment.