Verified Commit 8b136a40 authored by Patrick van der Leer's avatar Patrick van der Leer
Browse files

Inital sloppy setup

parents
Pipeline #266 failed with stages
in 25 seconds
# Created by .ignore support plugin (hsz.mobi)
### VirtualEnv template
# Virtualenv
# http://iamzed.com/2009/05/07/a-primer-on-virtualenv/
.Python
[Bb]in
[Ii]nclude
[Ll]ib
[Ll]ib64
[Ll]ocal
[Ss]cripts
pyvenv.cfg
.venv
pip-selfcheck.json
### Dropbox template
# Dropbox settings and caches
.dropbox
.dropbox.attr
.dropbox.cache
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff:
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/dictionaries
# Sensitive or high-churn files:
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
# Gradle:
.idea/**/gradle.xml
.idea/**/libraries
# CMake
cmake-build-debug/
cmake-build-release/
# Mongo Explorer plugin:
.idea/**/mongoSettings.xml
## File-based project format:
*.iws
## Plugin-specific files:
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### Python template
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
### Redis template
# Ignore redis binary dump (dump.rdb) files
*.rdb
### NotepadPP template
# Notepad++ backups #
*.bak
### Windows template
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msm
*.msp
# Windows shortcuts
*.lnk
### Eclipse template
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# CDT- autotools
.autotools
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
### Archives template
# It's better to unpack these files and commit the raw source because
# git has its own built in compression methods.
*.7z
*.jar
*.rar
*.zip
*.gz
*.tgz
*.bzip
*.bz2
*.xz
*.lzma
*.cab
# Packing-only formats
*.iso
*.tar
# Package management formats
*.dmg
*.xpi
*.gem
*.egg
*.deb
*.rpm
*.msi
*.msm
*.msp
### Vagrant template
# General
.vagrant/
# Log files (if you are creating logs in debug mode, uncomment this)
# *.logs
### Autotools template
# http://www.gnu.org/software/automake
Makefile.in
/ar-lib
/mdate-sh
/py-compile
/test-driver
/ylwrap
# http://www.gnu.org/software/autoconf
/autom4te.cache
/autoscan.log
/autoscan-*.log
/aclocal.m4
/compile
/config.guess
/config.h.in
/config.sub
/configure
/configure.scan
/depcomp
/install-sh
/missing
/stamp-h1
# https://www.gnu.org/software/libtool/
/ltmain.sh
# http://www.gnu.org/software/texinfo
/texinfo.tex
# http://www.gnu.org/software/m4/
m4/libtool.m4
m4/ltoptions.m4
m4/ltsugar.m4
m4/ltversion.m4
m4/lt~obsolete.m4
autom4te.cache
### Linux template
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="Flask">
<option name="enabled" value="true" />
</component>
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="TemplatesService">
<option name="TEMPLATE_CONFIGURATION" value="Jinja2" />
<option name="TEMPLATE_FOLDERS">
<list>
<option value="$MODULE_DIR$/templates" />
</list>
</option>
</component>
<component name="TestRunnerService">
<option name="PROJECT_TEST_RUNNER" value="Unittests" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="PROJECT" charset="UTF-8" />
</component>
</project>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyCompatibilityInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ourVersions">
<value>
<list size="2">
<item index="0" class="java.lang.String" itemvalue="2.7" />
<item index="1" class="java.lang.String" itemvalue="3.6" />
</list>
</value>
</option>
</inspection_tool>
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredPackages">
<value>
<list size="9">
<item index="0" class="java.lang.String" itemvalue="bs4" />
<item index="1" class="java.lang.String" itemvalue="pymysql" />
<item index="2" class="java.lang.String" itemvalue="xvfb" />
<item index="3" class="java.lang.String" itemvalue="yappi" />
<item index="4" class="java.lang.String" itemvalue="BeautifulSoup4" />
<item index="5" class="java.lang.String" itemvalue="lxml" />
<item index="6" class="java.lang.String" itemvalue="cryptography" />
<item index="7" class="java.lang.String" itemvalue="mutagen" />
<item index="8" class="java.lang.String" itemvalue="pydub" />
</list>
</value>
</option>
</inspection_tool>
</profile>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.6 (ebookhub-backend)" project-jdk-type="Python SDK" />
<component name="VagrantProjectSettings">
<option name="instanceFolder" value="" />
<option name="provider" value="" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/ebookhub-backend.iml" filepath="$PROJECT_DIR$/.idea/ebookhub-backend.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
# -*- coding: utf-8 -*-
"""Create an application instance."""
from eBookHub import init as create_app
from eBookHub.utils import get_config
config = get_config()
app = create_app(config)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000)
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask
from flask_cors import CORS
from eBookHub.config import ProdConfig
from . import extensions as ext
from .extensions import db
def init(config_object=ProdConfig):
"""An application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/.
:param config_object: The configuration object to use.
"""
app = Flask(__name__)
app.config.from_object(config_object)
app.config['intercept_exceptions'] = False
app.config['SENTRY_CONFIG']['environment'] = app.config.get("STAGE", "unknown")
if "DEBUG_TB_PANELS" in app.config.keys() and isinstance(app.config['DEBUG_TB_PANELS'], list):
app.config['DEBUG_TB_PANELS'].append('flask_mongoengine.panels.MongoDebugPanel')
CORS(app, resources={r'/api/*': {"origins": "*"}})
configure_extensions(app)
configure_logging(app)
configure_error_handlers(app)
configure_blueprints(app)
configure_shellcontext(app)
return app
def configure_blueprints(app):
""" Configure blueprints. """
pass
def configure_extensions(app):
"""Configure Flask extensions."""
ext.bcrypt.init_app(app)
ext.cache.init_app(app)
ext.db.init_app(app)
ext.migrate.init_app(app, db)
ext.login_manager.init_app(app)
ext.redis.init_app(app)
if app.config.get("SENTRY") and not app.testing:
ext.sentry.init_app(app)
if app.config['DEBUG_TB_ENABLED']:
from flask_debugtoolbar import DebugToolbarExtension
debug_toolbar = DebugToolbarExtension()
debug_toolbar.init_app(app)
return None
def post_configure_extensions(app):
def json_extract(item, key):
import json
j = json.loads(item)
value = j.get(key)
return value
import sqlalchemy
engine = ext.db.get_engine(app=app)
@sqlalchemy.event.listens_for(engine, "begin")
def do_begin(conn):
if conn.dialect.name == 'sqlite':
conn.connection.create_function('jsonExtract', 2, json_extract)
def configure_shellcontext(app):
"""Configure shell context objects."""
def shell_context():
"""Shell context objects."""
return {
'db': db
}
app.shell_context_processor(shell_context)
def configure_logging(app):
""" Configure logging. """
# Skip logging configuration for debug mode.
# if app.debug or not app.config['FILE_LOGGING']:
# return
if "GUNICORN_LOGGING" in app.config.keys() and app.config['GUNICORN_LOGGING']:
gunicorn_error_logger = logging.getLogger('gunicorn.error')
app.logger.handlers.extend(gunicorn_error_logger.handlers)
# http://flask.pocoo.org/docs/errorhandling/
loglvl = logging.INFO
if app.debug:
loglvl = logging.DEBUG
app.logger.setLevel(loglvl)
config = app.config
console = logging.StreamHandler()
console.setLevel(loglvl)
console.setFormatter(logging.Formatter('%(asctime)s %(levelname)s::%(message)s', '%H:%M:%S'))
app.logger.addHandler(console)
if app.config['FILE_LOGGING']:
log_file_handler = RotatingFileHandler(
config['LOG_PATH'],
maxBytes=config['LOG_MAX_BYTES'],
backupCount=config['LOG_BACKUP_COUNT']
)
log_file_handler.setLevel(loglvl)
log_file_handler.setFormatter(
logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
app.logger.addHandler(log_file_handler)
# -*- coding: utf-8 -*-
"""Application configuration."""
import os
import multiprocessing as mp
from flask_env import MetaFlaskEnv
class Config(metaclass=MetaFlaskEnv):
"""Base configuration."""
ENV_PREFIX = 'EBOOKHUB_BACKEND_'
PROJECT_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
DEBUG = False
SERVER_NAME = None
# Logging
LOG_FOLDER = "logs"
FILE_LOGGING = True
try:
if not os.path.exists(LOG_FOLDER) or not os.access(LOG_FOLDER, os.W_OK):
os.mkdir(LOG_FOLDER)
except OSError as e:
FILE_LOGGING = False
LOG_NAME = 'info.log'
LOG_PATH = os.path.join(LOG_FOLDER, LOG_NAME)
LOG_MAX_BYTES = 0
LOG_BACKUP_COUNT = 0
# Flask-Cache: http://pythonhosted.org/Flask-Cache/
# Can be "memcached", "redis", etc.
CACHE_TYPE = 'simple'
CACHE_DEFAULT_TIMEOUT = 60
# Flask-SQLAlchemy: http://packages.python.org/Flask-SQLAlchemy/config.html
SQLALCHEMY_DATABASE_URI = None
SQLALCHEMY_ECHO = False
SQLALCHEMY_TRACK_MODIFICATIONS = False
# Flask-Login: http://flask.pocoo.org/docs/quickstart/#sessions
SECRET_KEY = os.environ.get(
'FLASK_SECRET_KEY',
'CjP6YrXaDq8nchVyCF4DEuzw8A9Gutmy5vnTWyXdHWts4TnqeE3' * mp.cpu_count()
)
APP_DIR = os.path.abspath(os.path.dirname(__file__)) # This directory
# BCrypt
BCRYPT_LOG_ROUNDS = 13
# Debug ToolBar
DEBUG_TB_ENABLED = False # Disable Debug toolbar
DEBUG_TB_INTERCEPT_REDIRECTS = False
# Babel i18n
BABEL_DEFAULT_LOCALE = 'en'