Beispiel #1
0
def create_app(config_mode="dev"):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)

    if config_mode == "dev":
        app.config.from_object(app_config.get("dev"))
    elif config_mode == "prod":
        app.config.from_object(app_config.get("prod"))
    else:
        raise Exception("Please Provide dev/prod config")

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    with app.app_context():
        from applications.home.views import home
        app.register_blueprint(home)
        from applications.dash.default import create_dashboard
        create_dashboard(app)
        from applications.dash.stocktoday import create_stock_app
        create_stock_app(app)
        return app
Beispiel #2
0
 async def get(self):
     code = self.get_argument('code')
     token_payload = {
         'client_id': app_config.get('AUTH_ID'),
         'client_secret': app_config.get('CLIENT_SECRET'),
         'code': code,
         'grant_type': 'authorization_code',
         'redirect_uri': app_config.get("REDIRECT_URL")
     }
     _url = "https://{domain}/oauth/token".format(
         domain=app_config.get("DOMIAN"))
     print(dumps(token_payload))
     response = await fetch(_url,
                            method='POST',
                            headers={'content-type': 'application/json'},
                            payload=dumps(token_payload))
     if response.code == 200:
         body = loads(response.body.decode('utf-8'))
         access_token = body['access_token']
         user = AuthUser(app_config.get('DOMIAN'), access_token, body)
         user_info = await user.get_or_create()
         tok = encode(dict(id=user_info.uid, token=user_info.token),
                      self.settings["jwt_secret"],
                      algorithm='HS256')
         print(tok)
         self.set_secure_cookie('_T_GA', tok)
         self.redirect('/')
     else:
         self.redirect('/')
Beispiel #3
0
def create_app(env_config=None):
    """Instantiate and return flask app"""

    app = Flask(__name__)
    
    # configure app object
    app.config.from_object(app_config.get(env_config\
        or os.getenv('FLASK_ENV')))

    # handle unknown url errors
    @app.errorhandler(404)
    def url_unknown(e):
        return jsonify(
            create_message(MSG['url_unknown'], error=True)
        ), 404

    # handle Internal Server Errors
    @app.errorhandler(500)
    def internal_server_error(e):
        return jsonify(
            create_message(MSG['internal_server_error'], error=True)
        ), 500

    # handle unauthorized method errors
    @app.errorhandler(405)
    def method_not_allowed(e):
        return jsonify(
            create_message(MSG['unsupported_action'], error=True)
        ), 405

    # register movies app
    app.register_blueprint(movies)

    return app
Beispiel #4
0
    def _update_text(self):
        from markdown2 import Markdown
        from html import escape
        from bs4 import BeautifulSoup
        import re

        if self.source is None:
            return
        if self.source_type == self.SOURCE_TYPE_MARKDOWN:

            class Converter(Markdown):
                def postprocess(self, text):
                    return re.compile(r'^<h1>CUT:?\s*(.*)?</h1>', flags=re.M)\
                        .sub((lambda m: r'<cut title="%s"/>' % escape(m.group(1))), text)

            self._text = Converter(extras=['fenced-code-blocks']).convert(
                self.source)
        elif self.source_type == self.SOURCE_TYPE_PLAINTEXT:
            self._text = escape(self.source)
        else:
            self._text = self.source
        cut = BeautifulSoup(self._text,
                            app_config.get('blog.html_parser')).find('cut')
        self.preview = cut and ''.join(
            reversed([str(e) for e in cut.previous_siblings]))
        self.read_more_label = cut and cut['title'] or None
        pass
Beispiel #5
0
def create_app(flask_env: FlaskEnv):
    """Create an app for the server to run."""

    # create app and Flask-RESTful Api instance
    app = Flask(__name__)

    # set up config based on flask_env
    config = app_config.get(flask_env)
    app.config.from_object(config)

    # for development server testing without having to rebuild react
    if flask_env == FlaskEnv.DEVELOPMENT:
        from flask_cors import CORS

        CORS(app, resources={r"/api/*": {"origins": "http://*****:*****@app.route("/")
    def serve_react():
        """Serve the built react app."""
        return send_file("index.html")

    @app.route("/robots.txt")
    def serve_robots():
        return send_file("static/robots.txt")

    @app.route("/manifest.json")
    def serve_manifest():
        return send_file("static/manifest.json")

    @app.route("/asset-manifest.txt")
    def serve_asset_manifest():
        return send_file("static/asset-manifest.txt")

    @app.route("/favicon/<icon_file>")
    def serve_favicon(icon_file):
        return send_file(f"static/favicon/{icon_file}")

    # make sure react router urls route back to react, and not to the server
    @app.route("/", defaults={"input_path": ""})
    @app.route("/<path:input_path>")
    def homepage(input_path):
        """Serve the built react app."""

        return send_file("index.html")

    return app
Beispiel #6
0
def create_app(debug=False, config_name='production'):
    app = Flask(__name__, instance_relative_config=True)

    # Loading config
    app.config.from_object(app_config.get(config_name))
    app.config.from_pyfile('config.py')
    if os.environ.get('FLASK_CONFIG_FILE', False):
        app.config.from_envvar('FLASK_CONFIG_FILE')
    print(app.config)
    return app
Beispiel #7
0
def note_feed():
    from pyatom import AtomFeed
    site_url = '://'.join(request.urlparts[:2])
    author = app_config.get('feed.author')
    db_session = Session()
    notes = db_session.query(Note).order_by(Note.created_at.desc()).limit(10).all()
    feed = AtomFeed(title=app_config.get('feed.title'),
                    subtitle=app_config.get('feed.subtitle'),
                    feed_url=site_url + app.get_url('note-feed'),
                    url=site_url + app.get_url('note-list'),
                    author=author)
    for note in notes:
        feed.add(title=note.title,
                 content=strip_cut(note.text),
                 content_type="html",
                 author=author,
                 url=site_url + app.get_url('note-details', note_id=note.id),
                 updated=note.created_at)
    response.add_header('Content-Type', 'application/atom+xml')
    return feed.to_string()
Beispiel #8
0
def create_app(env):
    app = Flask(__name__)
    app.config.from_object(app_config.get(env))

    from harvestapi.app import api_bp
    app.register_blueprint(api_bp, url_prefix='/harvest')

    from harvestapi.model import db
    db.init_app(app)

    return app
Beispiel #9
0
def note_feed():
    from pyatom import AtomFeed
    site_url = '://'.join(request.urlparts[:2])
    author = app_config.get('feed.author')
    db_session = Session()
    notes = db_session.query(Note).order_by(
        Note.created_at.desc()).limit(10).all()
    feed = AtomFeed(title=app_config.get('feed.title'),
                    subtitle=app_config.get('feed.subtitle'),
                    feed_url=site_url + app.get_url('note-feed'),
                    url=site_url + app.get_url('note-list'),
                    author=author)
    for note in [n for n in notes if not n.is_draft]:
        feed.add(title=note.title,
                 content=strip_cut(note.text),
                 content_type="html",
                 author=author,
                 url=site_url + app.get_url('note-details', note_id=note.id),
                 updated=note.created_at)
    response.add_header('Content-Type', 'application/atom+xml')
    return feed.to_string()
Beispiel #10
0
def login():
    username = post_get('username')
    password = post_get('password').encode('utf-8')
    if (username and password) is not None:
        hashed = app_config.get('app.auth.%s' % username).encode('utf-8')
        if bcrypt.hashpw(password, hashed) == hashed:
            s = get_session()
            s['authenticated'] = True
            s['username'] = username
            s.save()
            bottle.redirect('/')
        else:
            return template('login.html')
Beispiel #11
0
def login():
    username = post_get('username')
    password = post_get('password').encode('utf-8')
    if (username and password) is not None:
        hashed = app_config.get('app.auth.%s' % username).encode('utf-8')
        if bcrypt.hashpw(password, hashed) == hashed:
            s = get_session()
            s['authenticated'] = True
            s['username'] = username
            s.save()
            bottle.redirect('/')
        else:
            return template('login.html')
def _init_test_db():
    import alembic.config
    import sqlalchemy

    from config import app_config

    # cleanup db
    engine = sqlalchemy.create_engine(app_config.get("db", "url"), echo=False)
    results = engine.execute("SHOW TABLES")
    for result in results:
        table = result[0]
        engine.execute(f"DROP TABLE IF EXISTS {table}")

    # migrate to head
    argv = [
        "upgrade",
        "head",
    ]
    alembic.config.main(argv=argv)
Beispiel #13
0
    def _update_text(self):
        from markdown2 import Markdown
        from html import escape
        from bs4 import BeautifulSoup
        import re

        if self.source is None:
            return
        if self.source_type == self.SOURCE_TYPE_MARKDOWN:
            class Converter(Markdown):
                def postprocess(self, text):
                    return re.compile(r'^<h1>CUT:?\s*(.*)?</h1>', flags=re.M)\
                        .sub((lambda m: r'<cut title="%s"/>' % escape(m.group(1))), text)
            self._text = Converter(extras=['fenced-code-blocks']).convert(self.source)
        elif self.source_type == self.SOURCE_TYPE_PLAINTEXT:
            self._text = escape(self.source)
        else:
            self._text = self.source
        cut = BeautifulSoup(self._text, app_config.get('blog.html_parser')).find('cut')
        self.preview = cut and ''.join(reversed([str(e) for e in cut.previous_siblings]))
        self.read_more_label = cut and cut['title'] or None
        pass
Beispiel #14
0
def create_app(config_name):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object(app_config.get(config_name))
    app.config.from_pyfile('config.py')

    Bootstrap(app)
    db.init_app(app)
    login_manager.init_app(app)
    login_manager.login_message = "You must be logged in to access this page."
    login_manager.login_view = "auth.login"
    migrate = Migrate(app, db)

    from app import models

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    from .home import home as home_blueprint
    app.register_blueprint(home_blueprint)

    @app.errorhandler(403)
    def forbidden(error):
        return render_template('errors/403.html', title='Forbidden'), 403

    @app.errorhandler(404)
    def page_not_found(error):
        return render_template('errors/404.html', title='Page Not Found'), 404

    @app.errorhandler(500)
    def internal_server_error(error):
        return render_template('errors/500.html', title='Server Error'), 500

    return app
Beispiel #15
0
#!/usr/bin/env python

import webapp2

from config import app_config
from handlers.Error import error_handlers
from routes import route_list

app = webapp2.WSGIApplication(
    routes=route_list,
    config=app_config,
    debug=app_config.get("debug", False),
)

app.error_handlers.update(error_handlers)
def session():
    url = app_config.get("db", "url")
    engine = sqlalchemy.create_engine(url, echo=False)

    Session = sqlalchemy.orm.sessionmaker(bind=engine)
    return Session()
Beispiel #17
0
import os
import json

import jinja2
import webapp2
 
import datetime as dt

from models import Admin
from lib import encrypt

from config import app_config as cfg

SUBMISSION_TIMEOUT = cfg.get('submission_timeout', 30)

template_dir = os.path.join(os.path.dirname(__file__), '../templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
															 autoescape = True)

class BaseHandler(webapp2.RequestHandler):
 def write(self, *a, **kw):
	self.response.write(*a, **kw)

 def render_str(self, template, **params):
	t = jinja_env.get_template(template)
	return t.render(params, admin=self.admin)

 def render(self, template, **kw):
	if not template.endswith('.html'):
	 template = template + '.html'
	self.response.write(self.render_str(template, **kw))
Beispiel #18
0
import json
from base import BaseHandler
from models import Admin

from lib import qr, ziplib

from config import app_config as cfg
from models import Location, Comfort
from google.appengine.api import memcache
from google.appengine.ext import db

MC_LOCATIONS_KEY = cfg.get('MC_LOCATIONS_KEY', '')
HOSTNAME = cfg.get('hostname', 'localhost')


def get_locations():
    locations = memcache.get(MC_LOCATIONS_KEY)
    if not locations:
        locations = list(Location.all())
        memcache.set(MC_LOCATIONS_KEY, locations)
    return locations


def login_required(f):
    def wrapper(self, *args, **kwargs):
        if not self.admin:
            self.redirect('/login')
        else:
            f(self, *args, **kwargs)

    return wrapper
Beispiel #19
0
# coding=utf-8

import webapp2
import logging

import fix_path

from routes import route_list
from config import app_config

app = webapp2.WSGIApplication(route_list,
                                config = app_config,
                                debug = app_config.get('debug', True))
Beispiel #20
0
    author = app_config.get('feed.author')
    db_session = Session()
    notes = db_session.query(Note).order_by(
        Note.created_at.desc()).limit(10).all()
    feed = AtomFeed(title=app_config.get('feed.title'),
                    subtitle=app_config.get('feed.subtitle'),
                    feed_url=site_url + app.get_url('note-feed'),
                    url=site_url + app.get_url('note-list'),
                    author=author)
    for note in [n for n in notes if not n.is_draft]:
        feed.add(title=note.title,
                 content=strip_cut(note.text),
                 content_type="html",
                 author=author,
                 url=site_url + app.get_url('note-details', note_id=note.id),
                 updated=note.created_at)
    response.add_header('Content-Type', 'application/atom+xml')
    return feed.to_string()


debug = app_config.get('app.debug', False)

if __name__ == '__main__':
    run(middleware,
        host='localhost',
        port=app_config.get('app.port', 5040),
        server=app_config.get('app.server', 'wsgiref'),
        debug=debug,
        reloader=debug)
else:
    application = middleware
Beispiel #21
0
 def __init__(self):
     host = app_config.get("KAFKA_SOCCER_HOST")
     # port = Config.KAFKA_SOCCER_PORT
     self.set_host(host)
Beispiel #22
0
from sqlalchemy import create_engine
from config import app_config
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy import Column, Integer, String, Text, DateTime, Boolean
from sqlalchemy.orm import sessionmaker
from datetime import datetime
from pytz import timezone

tzlocal = timezone(app_config.get('app.timezone', 'UTC'))

Base = declarative_base()

engine = create_engine('sqlite:///%s' %
                       app_config.get('app.db.path', ':memory:'),
                       echo=True,
                       encoding='utf-8')
Session = sessionmaker(bind=engine)


class Note(Base):
    __tablename__ = 'notes'

    SOURCE_TYPE_MARKDOWN = 1
    SOURCE_TYPE_HTML = 2
    SOURCE_TYPE_PLAINTEXT = 3

    id = Column(Integer, primary_key=True)
    source = Column(Text)
    _source_type = Column('source_type', Integer)
    _text = Column('text', Text)
from args import parser, get_config_module
import hashlib
import hmac
import sys
import requests
import urllib

parser.add_argument("path", metavar="P", type=str, help="Path to query metadata of")
vals = parser.parse_args()
config = get_config_module(vals.config)
path = vals.path

try:
    from config import app_config
    key = app_config["PUBLISHER_SECRET_KEY"]
    root = app_config.get("APPLICATION_ROOT", "")
except ImportError, KeyError:
    print "Unable to retrieve secret key for metadata request"
    sys.exit(1)

try:
    from config import host_config
    if "host" in host_config:
        host = host_config["host"]
    else:
        host = "127.0.0.1"

    if "port" in host_config:
        port = host_config["port"]
    else:
        port = 8000
Beispiel #24
0
import vertx
from config import app_config

vertx.deploy_verticle('WebSocketServer.py',app_config.get('socket.config'),1)
vertx.deploy_verticle('HttpServer.py',app_config.get('http.config'),1)
vertx.deploy_verticle('HttpClient.py',app_config.get('http.client.config'),1)
Beispiel #25
0
#!/usr/bin/env python
#
import webapp2
import logging
import fix_path

from routes import route_list
from config import app_config

log = logging.getLogger(__name__)

app = webapp2.WSGIApplication(route_list,
				config = app_config,
				debug = app_config.get('debug', False))
Beispiel #26
0
def production():
    env.hosts = [app_config.get('deploy.production.host')]
    env.key_filename = app_config.get('deploy.production.key_file')
    conf['code_dir'] = app_config.get('deploy.production.target_dir')
Beispiel #27
0
def production():
    env.hosts = [app_config.get('deploy.production.host')]
    env.key_filename = app_config.get('deploy.production.key_file')
    conf['code_dir'] = app_config.get('deploy.production.target_dir')
Beispiel #28
0
from datetime import datetime, timedelta
from string import capitalize

from config import app_config as cfg
from lib import errors, valid
from base import BaseHandler, BaseComfortHandler
from models import Comfort, Location, Admin
from google.appengine.api import memcache

MC_LOCATIONS_KEY = cfg.get('MC_LOCATIONS_KEY', '')
MC_GRAPH_DATA_KEY = cfg.get('MC_GRAPH_DATA_KEY', '')
MAX_RECORDS = cfg.get('data_api_max_records', 100)
GRAPH_REFRESH = cfg.get('graph_refresh', 5)

GREATER_THAN = 'g'
LESS_THAN = 'l'
FROM = 'from'
TO = 'to'
DELIMITER = '-'

class LocationsAPI(BaseHandler):
	def get(self):
		"""The API to get the list of locations from the database. The following
		parameters can be specified:
			building 		- (optional) the list of locations for the building
			floor 			- (optional) the list of locations for the building and floor
		Returns a list of locations in JSON format. An empty list will be returned
		if there are no results for the specified parameters."""
		locations = memcache.get(MC_LOCATIONS_KEY)

		if not locations:
Beispiel #29
0
    author = app_config.get('feed.author')
    db_session = Session()
    notes = db_session.query(Note).order_by(Note.created_at.desc()).limit(10).all()
    feed = AtomFeed(title=app_config.get('feed.title'),
                    subtitle=app_config.get('feed.subtitle'),
                    feed_url=site_url + app.get_url('note-feed'),
                    url=site_url + app.get_url('note-list'),
                    author=author)
    for note in notes:
        feed.add(title=note.title,
                 content=strip_cut(note.text),
                 content_type="html",
                 author=author,
                 url=site_url + app.get_url('note-details', note_id=note.id),
                 updated=note.created_at)
    response.add_header('Content-Type', 'application/atom+xml')
    return feed.to_string()


debug = app_config.get('app.debug', False)

if __name__ == '__main__':
    run(middleware,
        host='localhost',
        port=app_config.get('app.port', 5040),
        server=app_config.get('app.server', 'wsgiref'),
        debug=debug,
        reloader=debug
        )
else:
    application = middleware
Beispiel #30
0
import os
from app import create_app
from flask.ext.script import Manager
from flask.ext.script import Shell
from flask.ext.script import Server
from config import app_config

config_object=app_config.get(os.environ.get('FLASK_CONIFG','default'))

app=create_app(config_object)

manager=Manager(app)

def make_shell():
	return dict(app=app)

manager.add_command('shell',Shell(make_context=make_shell))
manager.add_command('runserver',Server(
	use_reloader=True,
	host='localhost',
	port=5000
))

if __name__=='__main__':
	manager.run()
Beispiel #31
0
 def __load_app_log_config(self):
     self.log_config = app_config.get("logging")
     self.CONF_LOG_LEVEL = self.log_config.get("log_level", None) or 'INFO'
     self.LOGGING_MAX_BYTES = 10 * 1024 * 1024
Beispiel #32
0
from datetime import datetime, timedelta
from string import capitalize

from config import app_config as cfg
from lib import errors, valid
from base import BaseHandler, BaseComfortHandler
from models import Comfort, Location, Admin
from google.appengine.api import memcache

MC_LOCATIONS_KEY = cfg.get('MC_LOCATIONS_KEY', '')
MC_GRAPH_DATA_KEY = cfg.get('MC_GRAPH_DATA_KEY', '')
MAX_RECORDS = cfg.get('data_api_max_records', 100)
GRAPH_REFRESH = cfg.get('graph_refresh', 5)

GREATER_THAN = 'g'
LESS_THAN = 'l'
FROM = 'from'
TO = 'to'
DELIMITER = '-'

class LocationsAPI(BaseHandler):
        def put(self):
                """Add a location to the database"""
                building = self.request.get('building')
                floor = self.request.get('floor')
                location = Location.create() # todo AM

                db.put(location)
                memcache.delete(MC_LOCATIONS_KEY)

        def get(self):
Beispiel #33
0
from config import app_config
from routes import route_list
from services.db_helper import DBHelper
import webapp2

db_helper = DBHelper()
app = webapp2.WSGIApplication(route_list, config=app_config, debug=app_config.get("debug", False))
Beispiel #34
0
import json
from base import BaseHandler
from models import Admin

from lib import qr, ziplib

from config import app_config as cfg
from models import Location, Comfort
from google.appengine.api import memcache
from google.appengine.ext import db

MC_LOCATIONS_KEY = cfg.get('MC_LOCATIONS_KEY', '')
HOSTNAME = cfg.get('hostname', 'localhost')

def get_locations():
	locations = memcache.get(MC_LOCATIONS_KEY)
	if not locations:
		locations = list(Location.all())
		memcache.set(MC_LOCATIONS_KEY, locations)
	return locations

def login_required(f):
	def wrapper(self, *args, **kwargs):
		if not self.admin:
			self.redirect('/login')
		else:
			f(self, *args, **kwargs)
	return wrapper

class AdminHandler(BaseHandler):
	def get_admin(self):
Beispiel #35
0
 def init_kafka(self):
     res = self.set_host(app_config.get("KAFKA_SOCCER_HOST"))
     if res is not None:
         logger.info("初始化kafka成功")
     else:
         logger.info("初始化kafka失败")
Beispiel #36
0
from sqlalchemy import create_engine
from config import app_config
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy import Column, Integer, String, Text, DateTime
from sqlalchemy.orm import sessionmaker
from datetime import datetime
from pytz import timezone

tzlocal = timezone(app_config.get('app.timezone', 'UTC'))

Base = declarative_base()

engine = create_engine('sqlite:///%s' % app_config.get('app.db.path', ':memory:'), echo=True, encoding='utf-8')
Session = sessionmaker(bind=engine)


class Note(Base):
    __tablename__ = 'notes'

    SOURCE_TYPE_MARKDOWN = 1
    SOURCE_TYPE_HTML = 2
    SOURCE_TYPE_PLAINTEXT = 3

    id = Column(Integer, primary_key=True)
    source = Column(Text)
    _source_type = Column('source_type', Integer)
    _text = Column('text', Text)
    preview = Column(Text)
    read_more_label = Column(String(255))
    created_at = Column(DateTime)
Beispiel #37
0
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.

# Overwrite the alembic.ini sqlalchemy.url
x_db_url = context.get_x_argument(as_dictionary=True).get('x_db_url')
if x_db_url:
    # > alembic -x x_db_url=DB_URL upgrade head
    config.set_main_option('sqlalchemy.url', x_db_url)
else:
    import os
    import sys
    sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
    from config import app_config
    config.set_main_option('sqlalchemy.url', app_config.get('db', 'url'))


def run_migrations_offline():
    """Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.

    Calls to context.execute() here emit the given string to the
    script output.

    """
    url = config.get_main_option("sqlalchemy.url")
Beispiel #38
0
#!/usr/bin/env python
#
import webapp2
import logging

#adjust library path before any other module gets imported...
import fix_path

from routes import route_list
from config import app_config

log = logging.getLogger(__name__)

app = webapp2.WSGIApplication(route_list,
				config = app_config,
				debug = app_config.get('debug', False))
from pymongo import MongoClient
from datetime import datetime, timedelta
import os
import sys
from config import app_config
from dotenv import load_dotenv
load_dotenv()

app_configuration = app_config.get(os.getenv("FLASK_ENV"))


def connect_mongo(tenant):
    client = MongoClient(app_configuration.MONGO_URI)
    db = client[f'{app_configuration.DB_NAME}_{tenant.lower()}']
    return db