Least change to adapt with python3

change some syntax
- except clause
- unicode -> bulitins.str
- sqllite uri
- fix import local path
- 01 to 1  (0 is meaningless)

add module
- future
- builtins (from future)
- imp (python3 )
- past (from future)
- sqlalchemy (update one)

refer to
http://python-future.org/compatible_idioms.html
This commit is contained in:
林檎 2017-03-05 17:40:39 +08:00
parent 8c7ba2ccdf
commit b70191ca2a
8 changed files with 39 additions and 21 deletions

4
cps.py
View File

@ -6,7 +6,9 @@ import sys
base_path = os.path.dirname(os.path.abspath(__file__)) base_path = os.path.dirname(os.path.abspath(__file__))
# Insert local directories into path # Insert local directories into path
sys.path.insert(0, os.path.join(base_path, 'vendor')) sys.path.append(base_path)
sys.path.append(os.path.join(base_path, 'cps'))
sys.path.append(os.path.join(base_path, 'vendor'))
from cps import web from cps import web
from tornado.wsgi import WSGIContainer from tornado.wsgi import WSGIContainer

View File

@ -14,28 +14,28 @@ try:
from wand.image import Image from wand.image import Image
from wand import version as ImageVersion from wand import version as ImageVersion
use_generic_pdf_cover = False use_generic_pdf_cover = False
except ImportError, e: except ImportError as e:
logger.warning('cannot import Image, generating pdf covers for pdf uploads will not work: %s', e) logger.warning('cannot import Image, generating pdf covers for pdf uploads will not work: %s', e)
use_generic_pdf_cover = True use_generic_pdf_cover = True
try: try:
from PyPDF2 import PdfFileReader from PyPDF2 import PdfFileReader
from PyPDF2 import __version__ as PyPdfVersion from PyPDF2 import __version__ as PyPdfVersion
use_pdf_meta = True use_pdf_meta = True
except ImportError, e: except ImportError as e:
logger.warning('cannot import PyPDF2, extracting pdf metadata will not work: %s', e) logger.warning('cannot import PyPDF2, extracting pdf metadata will not work: %s', e)
use_pdf_meta = False use_pdf_meta = False
try: try:
import epub import epub
use_epub_meta = True use_epub_meta = True
except ImportError, e: except ImportError as e:
logger.warning('cannot import epub, extracting epub metadata will not work: %s', e) logger.warning('cannot import epub, extracting epub metadata will not work: %s', e)
use_epub_meta = False use_epub_meta = False
try: try:
import fb2 import fb2
use_fb2_meta = True use_fb2_meta = True
except ImportError, e: except ImportError as e:
logger.warning('cannot import fb2, extracting fb2 metadata will not work: %s', e) logger.warning('cannot import fb2, extracting fb2 metadata will not work: %s', e)
use_fb2_meta = False use_fb2_meta = False
@ -48,7 +48,7 @@ def process(tmp_file_path, original_file_name, original_file_extension):
return epub.get_epub_info(tmp_file_path, original_file_name, original_file_extension) return epub.get_epub_info(tmp_file_path, original_file_name, original_file_extension)
if ".FB2" == original_file_extension.upper() and use_fb2_meta is True: if ".FB2" == original_file_extension.upper() and use_fb2_meta is True:
return fb2.get_fb2_info(tmp_file_path, original_file_extension) return fb2.get_fb2_info(tmp_file_path, original_file_extension)
except Exception, e: except Exception as e:
logger.warning('cannot parse metadata, using default: %s', e) logger.warning('cannot parse metadata, using default: %s', e)
return default_meta(tmp_file_path, original_file_name, original_file_extension) return default_meta(tmp_file_path, original_file_name, original_file_extension)

View File

@ -294,7 +294,8 @@ def setup_db():
return False return False
dbpath = os.path.join(config.config_calibre_dir, "metadata.db") dbpath = os.path.join(config.config_calibre_dir, "metadata.db")
engine = create_engine('sqlite:///{0}'.format(dbpath.encode('utf-8')), echo=False, isolation_level="SERIALIZABLE") #engine = create_engine('sqlite:///{0}'.format(dbpath.encode('utf-8')), echo=False, isolation_level="SERIALIZABLE")
engine = create_engine('sqlite:///'+ dbpath, echo=False, isolation_level="SERIALIZABLE")
try: try:
conn = engine.connect() conn = engine.connect()

View File

@ -37,16 +37,16 @@ def get_fb2_info(tmp_file_path, original_file_extension):
first_name = u'' first_name = u''
return first_name + ' ' + middle_name + ' ' + last_name return first_name + ' ' + middle_name + ' ' + last_name
author = unicode(", ".join(map(get_author, authors))) author = str(", ".join(map(get_author, authors)))
title = tree.xpath('/fb:FictionBook/fb:description/fb:title-info/fb:book-title/text()', namespaces=ns) title = tree.xpath('/fb:FictionBook/fb:description/fb:title-info/fb:book-title/text()', namespaces=ns)
if len(title): if len(title):
title = unicode(title[0]) title = str(title[0])
else: else:
title = u'' title = u''
description = tree.xpath('/fb:FictionBook/fb:description/fb:publish-info/fb:book-name/text()', namespaces=ns) description = tree.xpath('/fb:FictionBook/fb:description/fb:publish-info/fb:book-name/text()', namespaces=ns)
if len(description): if len(description):
description = unicode(description[0]) description = str(description[0])
else: else:
description = u'' description = u''

View File

@ -13,11 +13,17 @@ import os
import traceback import traceback
import re import re
import unicodedata import unicodedata
from StringIO import StringIO try:
from StringIO import StringIO
from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
except ImportError:
from io import StringIO
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import encoders from email import encoders
from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.generator import Generator from email.generator import Generator
from email.utils import formatdate from email.utils import formatdate
from email.utils import make_msgid from email.utils import make_msgid
@ -147,7 +153,7 @@ def send_raw_email(kindle_mail, msg):
smtplib.stderr = org_stderr smtplib.stderr = org_stderr
except (socket.error, smtplib.SMTPRecipientsRefused, smtplib.SMTPException), e: except (socket.error, smtplib.SMTPRecipientsRefused, smtplib.SMTPException) as e:
app.logger.error(traceback.print_exc()) app.logger.error(traceback.print_exc())
return _("Failed to send mail: %s" % str(e)) return _("Failed to send mail: %s" % str(e))
@ -239,7 +245,7 @@ def get_valid_filename(value, replace_whitespace=True):
value=value.replace(u'ß',u'ss') value=value.replace(u'ß',u'ss')
value = unicodedata.normalize('NFKD', value) value = unicodedata.normalize('NFKD', value)
re_slugify = re.compile('[\W\s-]', re.UNICODE) re_slugify = re.compile('[\W\s-]', re.UNICODE)
value = unicode(re_slugify.sub('', value).strip()) value = str(re_slugify.sub('', value).strip())
if replace_whitespace: if replace_whitespace:
#*+:\"/<>? werden durch _ ersetzt #*+:\"/<>? werden durch _ ersetzt
value = re.sub('[\*\+:\\\"/<>\?]+', u'_', value, flags=re.U) value = re.sub('[\*\+:\\\"/<>\?]+', u'_', value, flags=re.U)

View File

@ -10,6 +10,7 @@ import os
import logging import logging
from werkzeug.security import generate_password_hash from werkzeug.security import generate_password_hash
from flask_babel import gettext as _ from flask_babel import gettext as _
from builtins import str
dbpath = os.path.join(os.path.normpath(os.path.dirname(os.path.realpath(__file__)) + os.sep + ".." + os.sep), "app.db") dbpath = os.path.join(os.path.normpath(os.path.dirname(os.path.realpath(__file__)) + os.sep + ".." + os.sep), "app.db")
engine = create_engine('sqlite:///{0}'.format(dbpath), echo=False) engine = create_engine('sqlite:///{0}'.format(dbpath), echo=False)
@ -90,7 +91,7 @@ class UserBase:
return False return False
def get_id(self): def get_id(self):
return unicode(self.id) return str(self.id)
def filter_language(self): def filter_language(self):
return self.default_language return self.default_language

View File

@ -48,11 +48,17 @@ from shutil import move, copyfile
from tornado.ioloop import IOLoop from tornado.ioloop import IOLoop
from tornado import version as tornadoVersion from tornado import version as tornadoVersion
try:
from imp import reload
from past.builtins import xrange
except:
pass
try: try:
from wand.image import Image from wand.image import Image
use_generic_pdf_cover = False use_generic_pdf_cover = False
except ImportError, e: except ImportError as e:
use_generic_pdf_cover = True use_generic_pdf_cover = True
from cgi import escape from cgi import escape
@ -2186,12 +2192,12 @@ def upload():
return redirect(url_for('index')) return redirect(url_for('index'))
try: try:
copyfile(meta.file_path, saved_filename) copyfile(meta.file_path, saved_filename)
except OSError, e: except OSError as e:
flash(_(u"Failed to store file %s (Permission denied)." % saved_filename), category="error") flash(_(u"Failed to store file %s (Permission denied)." % saved_filename), category="error")
return redirect(url_for('index')) return redirect(url_for('index'))
try: try:
os.unlink(meta.file_path) os.unlink(meta.file_path)
except OSError, e: except OSError as e:
flash(_(u"Failed to delete file %s (Permission denied)." % meta.file_path), category="warning") flash(_(u"Failed to delete file %s (Permission denied)." % meta.file_path), category="warning")
file_size = os.path.getsize(saved_filename) file_size = os.path.getsize(saved_filename)
@ -2223,7 +2229,7 @@ def upload():
db.session.add(db_language) db.session.add(db_language)
# combine path and normalize path from windows systems # combine path and normalize path from windows systems
path = os.path.join(author_dir, title_dir).replace('\\','/') path = os.path.join(author_dir, title_dir).replace('\\','/')
db_book = db.Books(title, "", db_author.sort, datetime.datetime.now(), datetime.datetime(101, 01, 01), 1, db_book = db.Books(title, "", db_author.sort, datetime.datetime.now(), datetime.datetime(101, 1, 1), 1,
datetime.datetime.now(), path, has_cover, db_author, [], db_language) datetime.datetime.now(), path, has_cover, db_author, [], db_language)
db_book.authors.append(db_author) db_book.authors.append(db_author)
if db_language is not None: if db_language is not None:

2
requirements.txt Normal file
View File

@ -0,0 +1,2 @@
future
sqlalchemy