示例#1
0
def main(sdk_path, test_path):
    sys.path.insert(0, sdk_path)
    import dev_appserver
    dev_appserver.fix_sys_path()
    sys.path.insert(1, os.path.join(os.path.abspath('.'), 'lib'))
    sys.path.insert(1, os.path.join(os.path.abspath('.')))

    try:
        import config
    except ImportError:
        raise Exception('Unable to load config module. Paths are most likely screwed up. Current path is: %r and has %r' % (
            os.path.abspath('.'), os.listdir(os.path.abspath('.'))
        ))
    config.enable_debug_panel = False

    #
    # This must always be imported first.
    from flask import logging

    from main import app

    logger = logging.create_logger(app)

    console = logging.StreamHandler()
    console.setLevel(logging.DEBUG)
    logger.addHandler(console)

    suite = unittest.loader.TestLoader().discover(test_path)
    unittest.TextTestRunner(verbosity=2).run(suite)
示例#2
0
文件: app.py 项目: echhost/flasker
 def logger(self):
     if self._logger and self._logger.name == self.logger_name:
         return self._logger
     with _logger_lock:
         if self._logger and self._logger.name == self.logger_name:
             return self._logger
         from flask.logging import create_logger
         self._logger = rv = create_logger(self)
         return rv
示例#3
0
文件: basebp.py 项目: gsk727/git
    def logger(self):
        """
        更为详细完整的代请见flask module的app.py文件
        """
        if self.__logger:
            return self.__logger

        if not self.__logger:   # 多线程创建
            _logger_lock.acquire() 
            if not self.__logger:
                self.__logger = logging.create_logger(self)
            _logger_lock.release()
       
        return self.logger
示例#4
0
文件: app.py 项目: Davmuz/flask
    def logger(self):
        """A :class:`logging.Logger` object for this application.  The
        default configuration is to log to stderr if the application is
        in debug mode.  This logger can be used to (surprise) log messages.
        Here some examples::

            app.logger.debug('A value for debugging')
            app.logger.warning('A warning ocurred (%d apples)', 42)
            app.logger.error('An error occoured')

        .. versionadded:: 0.3
        """
        if self._logger and self._logger.name == self.logger_name:
            return self._logger
        with _logger_lock:
            if self._logger and self._logger.name == self.logger_name:
                return self._logger
            from flask.logging import create_logger
            self._logger = rv = create_logger(self)
            return rv
示例#5
0
from flask import Flask, url_for
#from flaskext.compass import Compass
from flask.logging import create_logger
from hackbox import template_helper
import os

app = Flask(__name__)
app.config.from_pyfile('config.py')
app.jinja_env.globals.update(helper=template_helper)

#app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension')

#compass = Compass(app)
logger = create_logger(app)

try:
	from flask_debugtoolbar import DebugToolbarExtension
	toolbar = DebugToolbarExtension(app)
except ImportError: pass

import hackbox.views
示例#6
0
# Author: Raul Gomez (rg9907)                                                 #
# Email: [email protected]                                                        #
################################################################################
"""
import logging
from logging import FileHandler
from flask import Flask
from flask.logging import create_logger
from app.routes import ROUTES, ERRORS
#from dotenv import load_dotenv

#load dev env vars
#load_dotenv()
# redirect http to https
APP = Flask(__name__)
LOG = create_logger(APP)

# Prevents print statement every time an endpoint is triggered.
logging.getLogger("werkzeug").setLevel(logging.DEBUG)
#logging.getLogger("werkzeug").setLevel(logging.WARNING)
APP.register_blueprint(ERRORS)
APP.register_blueprint(ROUTES, url_prefix="/otf/vth/oran/a1/v1")

if __name__ == '__main__':
    LOG_HANDLER = FileHandler('a1-policy-manager.log', mode='a')
    LOG_HANDLER.setLevel(logging.INFO)
    LOG.setLevel(logging.INFO)
    LOG.addHandler(LOG_HANDLER)
    #context = ('opt/cert/otf.pem', 'opt/cert/privateKey.pem')
    # app.run(debug = False, host = '0.0.0.0', port = 5000, ssl_context = context)
    APP.run(debug=False, host='0.0.0.0', port=6000)
示例#7
0
from flask import Flask, request, jsonify
from flask.logging import create_logger
import logging

import pandas as pd
from sklearn.externals import joblib
from sklearn.preprocessing import StandardScaler

app = Flask(__name__)
LOG = create_logger(app)
LOG.setLevel(logging.INFO)


def scale(payload):
    """Scales Payload"""

    LOG.info(f"Scaling Payload: \n{payload}")
    scaler = StandardScaler().fit(payload.astype(float))
    scaled_adhoc_predict = scaler.transform(payload.astype(float))
    return scaled_adhoc_predict


@app.route("/")
def home():
    html = "<h3>Sklearn Prediction Home</h3>"
    return html.format(format)


@app.route("/predict", methods=['POST'])
def predict():
    """Performs an sklearn prediction
Work to replace https://www.openarchives.org/Register/ValidateSite

reCaptcha support based on flask-wtf example code from
https://github.com/lepture/flask-wtf/tree/master/examples/recaptcha
"""
from flask import Flask, render_template, flash, session, redirect, url_for, logging
from wtforms import TextAreaField
from wtforms.validators import DataRequired
from flask.ext.wtf import Form
from flask.ext.wtf.recaptcha import RecaptchaField
import os.path
import uuid

app = Flask(__name__)
logger = logging.create_logger(app) #FIXME - what is best way to set this up?
cfg = 'oaipmh_validation_service.cfg'
app.config.from_pyfile(cfg+'_default') #assume default always present
app.config.from_pyfile(cfg, silent=True) #override for real config

class ValidateForm(Form):

    base_url = TextAreaField("baseURL", validators=[DataRequired()])
    recaptcha = RecaptchaField()

@app.route("/")
def index():
    return redirect(url_for("validate"))

@app.route("/pmh/validate")
def validate(form=None):
示例#9
0
from src.lib import exceptions
from src.lib.json import ApiJSONEncoder
from src.lib.response import ApiResponse
from src.lib.mongo import create_collections

app = Flask("app")
client = MongoClient(Config.DB_HOST, Config.DB_PORT)
db = client[Config.DB_NAME]

from src.todo.views import ListAPI, ItemAPI
from src.todo.collections import List, Item

create_collections(db, List)
create_collections(db, Item)

create_logger(app)

app.config.from_object(Config)
app.json_encoder = ApiJSONEncoder
app.response_class = ApiResponse

list_view = ListAPI.as_view('lists_api')
app.add_url_rule('/api/lists', view_func=list_view, methods=['GET', 'POST'])
app.add_url_rule('/api/lists/<string:list_id>',
                 view_func=list_view,
                 methods=['GET', 'PUT', 'DELETE'])

item_view = ItemAPI.as_view('item_api')
app.add_url_rule('/api/items', view_func=item_view, methods=['POST'])
app.add_url_rule('/api/items/<string:item_id>',
                 view_func=item_view,
示例#10
0
    }
    Talisman(app, content_security_policy=csp)
    app.config.from_pyfile(config_filename)

    db.init_app(app)

    app.register_blueprint(main)
    register_rq_dashboard(app)

    with app.app_context():
        db.create_all()

    return app


def register_rq_dashboard(app):
    app.config.from_object(rq_dashboard.default_settings)
    app.config["RQ_DASHBOARD_REDIS_URL"] = REDIS_URL

    @rq_dashboard.blueprint.before_request
    def requires_auth():
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return auth_response()

    app.register_blueprint(rq_dashboard.blueprint, url_prefix="/rq")


app = create_app("config.py")
log = create_logger(app)
示例#11
0
def create_app(
    session_manager: db.SessionManager,
    allowed_domain: str,
    mail: Union[mailer.SMTPMailer, mailer.PrintMailer] = mailer.PrintMailer(),
):
    # pylint: disable=unused-variable
    app = Flask(__name__)
    logger = create_logger(app)
    sm = session_manager

    logger.info("Using %s for mail" % mail)

    @app.route("/start/<int:user_id>/<uuid:secondary_id>",
               methods=["POST", "GET"])
    def start(user_id: int, secondary_id: uuid.UUID):
        session = sm.session(user_id, secondary_id)
        if session is None:
            abort(404)

        # Handle other states that shouldn't go to /start.
        if session.state is db.SessionState.WAITING_ON_CODE:
            return redirect_to_verify(user_id, secondary_id)
        if session.state in (db.SessionState.VERIFIED,
                             db.SessionState.COMPLETED):
            return redirect(url_for("success"), code=303)
        if session.state is db.SessionState.FAILED:
            return redirect(url_for("failure"), code=303)

        assert session.state is db.SessionState.WAITING_ON_START

        if request.method == "POST":
            email_addr = request.form["email"]
            if not email_addr.endswith(allowed_domain):
                # TODO: error feedback
                return redirect(url_for("start",
                                        user_id=user_id,
                                        secondary_id=secondary_id),
                                code=303)

            logger.info(
                f"User {session.discord_name} with id {session.user_id} sent an email"
            )
            mail.send(email_addr, session.verification_code,
                      session.discord_name)
            sm.set_email_sent(user_id, secondary_id)
            return redirect_to_verify(user_id, secondary_id)
        else:
            return render_template("start.html")

    @app.route("/verify/<int:user_id>/<uuid:secondary_id>", methods=["POST"])
    def verify_post(user_id: int, secondary_id: uuid.UUID):
        # Post-Redirect-Get pattern
        attempted_code: str = request.form["verification"]
        verification_result = sm.verify(user_id, secondary_id, attempted_code)

        if verification_result is True:
            return redirect(url_for("success"), code=303)
        elif verification_result == 0:
            # TODO: give 400 error? But who cares
            return redirect(url_for("failure"), code=303)
        else:
            return redirect_to_verify(user_id, secondary_id)

    @app.route("/verify/<int:user_id>/<uuid:secondary_id>", methods=["GET"])
    def verify_get(user_id: int, secondary_id: uuid.UUID):
        session = sm.session(user_id, secondary_id)
        if session is None:
            abort(404)

        remaining_attempts = session.remaining_attempts
        if remaining_attempts is None:
            abort(404)

        assert remaining_attempts >= 0

        # Handle other states that shouldn't go to /verify
        if remaining_attempts == 0 or session.state == db.SessionState.FAILED:
            return redirect(url_for("failure"), code=303)
        if session.state == db.SessionState.VERIFIED:
            return redirect(url_for("success"), code=303)
        if session.state == db.SessionState.WAITING_ON_START:
            return redirect(url_for("start",
                                    user_id=user_id,
                                    secondary_id=secondary_id),
                            code=303)

        return render_template(
            "verify.html",
            remaining_attempts=remaining_attempts,
        ), 200

    @app.route("/success")
    def success():
        response = app.make_response(
            render_template("passed_verification.html"))
        set_cache(response)
        return response

    @app.route("/failure")
    def failure():
        response = app.make_response(
            render_template("failed_verification.html"))
        set_cache(response)
        return response

    @app.route("/")
    def root():
        response = app.make_response(render_template("index.html"))
        set_cache(response)
        return response

    @app.errorhandler(404)
    def page_not_found(e):
        return render_template("404.html"), 404

    return app
示例#12
0
文件: app.py 项目: lingzhu1997/Agile
#app = Flask(__name__)

app.config['MONGO_DBNAME'] = "foodb"
app.config[
    'MONGO_URI'] = "mongodb+srv://admin:[email protected]/foodb?retryWrites=true&w=majority"

app.config[
    'SECRET_KEY'] = 'enydM2ANhdcoKwdVa0mWvEsbPFuQpMjf'  # Create your own.
app.config['SESSION_PROTECTION'] = 'strong'
#mongo = PyMongo(app)

# Use Flask-Login to track current user in Flask's session.
login_manager = LoginManager()
login_manager.setup_app(app)
login_manager.login_view = 'login'
LOG = logging.create_logger(app)
mongo = PyMongo(app)


@app.route('/')
def index():
    return redirect(url_for('products_list'))


@app.route('/products/')
def products_list():
    """Provide HTML listing of all Products."""
    # Query: Get all Products objects, sorted by date.
    products = mongo.db.products.find()[:]
    return render_template('product/index.html', products=products)
示例#13
0
import json

from flask import Flask, request, jsonify, abort
from flask.logging import create_logger

from backend.session_handler import create_session, load_session_file, save_session_file
from backend.lang.CastleVisitor import evaluate_expression
from backend.lang.structures import CastleException

application = Flask(__name__)
LOG = create_logger(application)


@application.route("/create-session", methods=["POST"])
def create():
    if request.method == "POST":

        session_id = create_session()

        response = jsonify({"id": session_id})
        response.headers.add("Access-Control-Allow-Origin", "*")

        return response
    else:
        LOG.error("This should be a POST request")


@application.route("/get-history", methods=["POST"])
def get_history():
    if request.method == "POST":
        # Extract Data
示例#14
0
"""
    App initialization.
"""

import logging
from logging.handlers import SMTPHandler, RotatingFileHandler
from flask.logging import create_logger
import os
from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

shocal = Flask(__name__)
logger = create_logger(shocal)
shocal.config.from_object(Config)
db = SQLAlchemy(shocal)
migrate = Migrate(shocal, db)

if not shocal.debug:
    if shocal.config['MAIL_SERVER']:
        auth = None
    if shocal.config['MAIL_USERNAME'] or shocal.config['MAIL_PASSWORD']:
        auth = (shocal.config['MAIL_USERNAME']
                or shocal.config['MAIL_PASSWORD'])
        secure = None
        if shocal.config['MAIL_USE_TLS']:
            secure = ()
            mail_handler = SMTPHandler(
                mailhost=(shocal.config['MAIL_SERVER'],
                          shocal.config['MAIL_PORT']),
示例#15
0
from flask import Flask, jsonify, request, logging

from callqueue.domain import parse_call
from callqueue.handler import WorkflowManager
from callqueue.database import InMemoryDatabase
from callqueue.queueservice import QueueService

app = Flask(__name__)
manager = WorkflowManager(InMemoryDatabase(),
                          QueueService(),
                          logger=logging.create_logger(app))


@app.route('/')
def index():
    return 'Hello World!'


@app.route('/queue', methods=['POST'])
def queue_call():
    body = request.json
    caller = parse_call(body)
    response = manager.greet_caller(caller)
    return jsonify(response)
示例#16
0
文件: routes.py 项目: vdrummer/human
from app import ap_parser
from app.db import get_db
from app import user_handler
from app import login_handler
from app import error_handler
from werkzeug.utils import secure_filename
from flask_login import LoginManager, UserMixin, logout_user, login_user, login_required, current_user
from datetime import timedelta
import json
import os
import io
import logging
from collections import Counter

# for flask run
app.logger = create_logger(app)

# when running gunicorn
# gunicorn_logger = logging.getLogger('gunicorn.error')
# app.logger = gunicorn_logger

## API routes
# Add custom api routes here. Be careful not to overwrite other routes or route function names.
#####################################

#####################################


@app.route('/api/callAPI', methods=["POST", "OPTIONS"])
def call_api():
    """
示例#17
0
def initlogging(app):
    import logging
    from logging import handlers
    from . import handlers as myojin_handlers

    # DEBUG flag is not True set several handler for production.
    if app.config.get('LOGGING_DEBUG',
                      False) or not app.config.get('DEBUG', True):
        if app.config.get('LOGGING_DEBUG') is True:
            from flask.logging import create_logger
            create_logger(app)
        else:
            del app.logger.handlers[:]

        import socket
        hostname = socket.gethostname()
        log_exc_mailto = app.config.get('LOGGING_EXCEPTION_MAILTO')
        if log_exc_mailto is not None:
            print >> sys.stderr, "register logging handler => exception mail to %s" % log_exc_mailto
            mh = myojin_handlers.MailHandler(
                app.config.get('MAIL_SENDER_FROM', '*****@*****.**'),
                log_exc_mailto, 'Application(%s) Failed on %s' % (
                    os.path.basename(app.root_path),
                    hostname,
                ))
            mh.setFormatter(logging.Formatter(SMTP_LOG_FORMAT))
            mh.setLevel(logging.ERROR)
            app.logger.addHandler(mh)

        log_filename = app.config.get('LOGGING_FILENAME', None)
        if log_filename is not None:
            print >> sys.stderr, "register logging handler => file to %s" % log_filename
            fh = handlers.TimedRotatingFileHandler(log_filename,
                                                   when='D',
                                                   interval=1,
                                                   backupCount=2)
            fh.setLevel(logging.DEBUG)
            fh.setFormatter(logging.Formatter(FILE_LOG_FORMAT))
            app.logger.addHandler(fh)

        log_syslog_host = app.config.get('LOGGING_SYSLOG_HOST', None)
        if log_syslog_host is not None:
            print >> sys.stderr, "register logging handler => syslog to %s" % str(
                log_syslog_host)
            sh = handlers.SysLogHandler(
                log_syslog_host,
                app.config.get('LOGGING_SYSLOG_CATEGORY', 'local0'))
            sh.setLevel(logging.DEBUG)
            sh.setFormatter(logging.Formatter(SYSLOG_FORMAT))
            app.logger.addHandler(sh)

        request_logging = app.config.get('LOGGING_REQUEST_ENABLED', True)
        if request_logging:
            ignore_urls = app.config.get('LOGGING_REQUEST_IGNORE_URLS')
            ignore_urls_string = " ".join(ignore_urls)

            from flask import request
            # setting before and after request functions
            REQUEST_START_LOGGING_FORMAT = "[REQSTART][%s] %04s %s"
            REQUEST_END_LOGGING_FORMAT = "[  REQEND][%s] %04s %s %s"

            current_user = app.current_user

            @app.before_request
            def before_request_logging():
                if request.url in ignore_urls_string: return

                try:
                    app.logger.debug(
                        REQUEST_START_LOGGING_FORMAT %
                        (repr(current_user).encode('utf-8', errors="ignore")
                         if current_user.is_authenticated() else "anonymous",
                         request.method, request.path))
                except:
                    import traceback
                    traceback.print_exc(file=sys.stderr)

            @app.after_request
            def after_request_logging(response):
                if request.url in ignore_urls_string: return

                try:
                    if response.status_code < 400:
                        app.logger.debug(
                            REQUEST_END_LOGGING_FORMAT %
                            (repr(current_user).encode('utf-8',
                                                       errors="ignore") if
                             current_user.is_authenticated() else "anonymous",
                             request.method, request.path,
                             response.status_code))
                    else:
                        app.logger.info(
                            REQUEST_END_LOGGING_FORMAT %
                            (repr(current_user).encode('utf-8',
                                                       errors="ignore") if
                             current_user.is_authenticated() else "anonymous",
                             request.method, request.path,
                             response.status_code))
                except:
                    import traceback
                    traceback.print_exc(file=sys.stderr)

                return response

#    print >>sys.stderr, "app.config['DEBUG'] => %s" % app.config.get('DEBUG')
#    print >>sys.stderr, "app.config['LOGGING_LEVEL'] => %s" % app.config.get('LOGGING_LEVEL')

    app.logger.setLevel(app.config.get('LOGGING_LEVEL', logging.DEBUG))

    print >> sys.stderr, "app.logger.effective_level: %s" % (
        logging.getLevelName(app.logger.getEffectiveLevel()))
    print >> sys.stderr, "app.logger.handlers: %s" % (app.logger.handlers)
    print >> sys.stderr, "app.logger initialized."
示例#18
0
def before_request():
    """
    リクエストの前処理
    """
    logger = logging.create_logger(current_app)
    logger.info(f"start {current_app.name} :: {request.json}")
示例#19
0
import json
import logging
from pathlib import Path
from typing import Dict

import markdown
from flask import render_template
from flask.logging import create_logger
from flask.templating import render_template_string

from app import app
from app.constants import BLOG_POST_DIRECTORY, NOTEBOOK_DIRECTORY, STATIC_DIRECTORY

logging.basicConfig(level=logging.INFO)
LOGGER = create_logger(app)

HTML = str


def extend_base_template(*args, **kwargs):
    """
    Passes all of the kwargs required by the base template,
    then continues with rendering the template
    """

    tab_contents = [
        {
            "name": "Home",
            "route": "/"
        },