Example #1
1
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    bootstrap.init_app(app)
    # mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    admin.init_app(app)
    # Todo-rezwan follow this guide for auto renewing session
    # http://stackoverflow.com/questions/19760486/resetting-the-expiration-time-for-a-cookie-in-flask
    # http://stackoverflow.com/questions/19760486/resetting-the-expiration-time-for-a-cookie-in-flask
    app.permanent_session_lifetime = timedelta(minutes=60)  # adding session time out. working

    # attach routes and custom error pages here
    from main import main as main_blueprint

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

    app.register_blueprint(auth_blueprint, url_prefix="/auth")
    from .admin import admin_panel as admin_blueprint

    app.register_blueprint(admin_blueprint, url_prefix="/admin")

    db.app = app
    db.create_all()

    return app
Example #2
1
def create_app(db_name=None):
    app = Flask(__name__)
    app.config.from_object(config)
    if db_name:
        config.MONGO_DATABASE = db_name

    mongo, db = HapPyMongo(config)
    app.permanent_session_lifetime = timedelta(hours=2)

    auth = CloudAuth(app, db)
    app.context_processor(template_functions.view_functions)

    Admin(app)

    @app.before_first_request
    def logger():
        if not app.debug:
            app.logger.addHandler(logging.StreamHandler())
            app.logger.setLevel(logging.INFO)

    @app.before_request
    def before_request():
        g.db, g.auth = db, auth

    defaults.application_initialize(db, app)
    views.BaseView.register(app)
    views.GlobalManageView.register(app)
    views.QueryView.register(app)

    if db_name:
        return app, db
    else:
        return app
def create_app(config_name):
    application = Flask(__name__, static_folder="static/", static_url_path=configs[config_name].STATIC_URL_PATH)

    init_app(
        application,
        configs[config_name],
        data_api_client=data_api_client,
        feature_flags=feature_flags,
        login_manager=login_manager,
    )
    application.permanent_session_lifetime = timedelta(hours=1)
    from .main import main as main_blueprint
    from .status import status as status_blueprint

    application.register_blueprint(status_blueprint, url_prefix="/suppliers")
    application.register_blueprint(main_blueprint, url_prefix="/suppliers")
    login_manager.login_view = "main.render_login"
    main_blueprint.config = application.config.copy()

    csrf.init_app(application)

    @application.before_request
    def remove_trailing_slash():
        if request.path.endswith("/"):
            return redirect(request.path[:-1], code=301)

    @application.before_request
    def refresh_session():
        session.permanent = True
        session.modified = True

    return application
Example #4
1
    def start():
        """
        Start the application
        """
        config_type = "DevelopmentConfig"
        if len(sys.argv) == 2:
            if sys.argv[1] == "dev":
                config_type = "DevelopmentConfig"
            elif sys.argv[1] == "test":
                config_type = "TestConfig"
            elif sys.argv[1] == "prod":
                config_type = "ProductionConfig"
        app = Flask(__name__)
        app.config.from_object("conf.config.%s" % config_type)
        app.secret_key = getRandomInteger(128)
        app.permanent_session_lifetime = timedelta(seconds=10)
        FORMAT = "%(asctime)s %(levelname)s: " "%(message)s [in %(pathname)s:%(lineno)d]"
        logging.basicConfig(filename=app.config["LOGFILE"], level=logging.DEBUG, format=FORMAT)
        PYSTHClient.init_controllers(app)

        @app.errorhandler(400)
        def bad_request(exception):
            """Bad Request"""
            data = dict(status=exception.code, error=str(exception), description=bad_request.__doc__)
            return jsonify(data), 400

        @app.errorhandler(404)
        def page_not_found(exception):
            """Page Not Found"""
            data = dict(status=exception.code, error=str(exception), description=page_not_found.__doc__)
            return jsonify(data), 404

        if app.config["DEBUG"] is True:

            @app.errorhandler(500)
            def error(exception):
                """Internal Server Error"""
                data = dict(status=exception.code, error=str(exception), description=error.__doc__)
                return jsonify(data), 500

        @app.errorhandler(403)
        def forbidden(exception):
            """Forbidden"""
            data = dict(status=exception.code, error=str(exception), description=forbidden.__doc__)
            return jsonify(data), 403

        # noinspection PyUnusedLocal
        @app.before_first_request
        def bootstrap():
            """
            Call the bootstrap function
            """
            Bootstrap()

        with app.app_context():
            Base.do_first_request()
        app.run(app.config["HOST"], app.config["PORT"])
 def setUp(self):
     application = Flask(__name__)
     application.config["TESTING"] = True
     application.secret_key = "you will not guess"
     application.permanent_session_lifetime = timedelta(seconds=1)
     self.application = application
     # Use an in memory database
     settings.EQ_SERVER_SIDE_STORAGE_DATABASE_URL = "sqlite://"
     self.session_manager = DatabaseSessionManager()
Example #6
1
    def flask(cls, name, config=None, debug=False, **kwargs):
        template_folder = kwargs.pop("template_folder", tmpl_dir)
        app = Flask(name, template_folder=template_folder, **kwargs)
        if config:
            app.config.from_object(config)
        app.permanent_session_lifetime = timedelta(minutes=60)
        app.debug = debug

        if app.config.get("COUCHDB_DATABASE", None) is None:
            app.config["COUCHDB_DATABASE"] = name.lower()

        assert app.secret_key is not None, "flask config does not specify a secret key"
        return app
Example #7
1
def create_app(config_name):
    application = Flask(__name__, static_folder="static/", static_url_path=configs[config_name].STATIC_URL_PATH)

    application.config["NOTIFY_ENVIRONMENT"] = config_name
    application.config.from_object(configs[config_name])

    init_app(application)
    csrf.init_app(application)

    @csrf.error_handler
    def csrf_handler(reason):
        if "user_id" not in session:
            application.logger.info(u"csrf.session_expired: Redirecting user to log in page")

            return application.login_manager.unauthorized()

        application.logger.info(
            u"csrf.invalid_token: Aborting request, user_id: {user_id}", extra={"user_id": session["user_id"]}
        )

        abort(400, reason)

    login_manager.init_app(application)
    admin_api_client.init_app(application)
    proxy_fix.init_app(application)

    from .main import main as main_blueprint

    application.permanent_session_lifetime = timedelta(hours=1)
    application.register_blueprint(main_blueprint, url_prefix="/admin")
    login_manager.login_view = "main.render_login"

    main_blueprint.config = application.config.copy()

    @application.before_request
    def remove_trailing_slash():
        if request.path != "/" and request.path.endswith("/"):
            return redirect(request.path[:-1], code=301)

    application.add_template_filter(datetimeformat)

    return application
def create_app(config_name):

    application = Flask(__name__, static_folder="static/", static_url_path=configs[config_name].STATIC_URL_PATH)

    init_app(
        application,
        configs[config_name],
        bootstrap=bootstrap,
        data_api_client=data_api_client,
        feature_flags=feature_flags,
        login_manager=login_manager,
    )
    # Should be incorporated into digitalmarketplace-utils as well
    csrf.init_app(application)

    application.permanent_session_lifetime = timedelta(hours=1)
    from .main import main as main_blueprint
    from .status import status as status_blueprint

    application.register_blueprint(status_blueprint, url_prefix="/admin")
    application.register_blueprint(main_blueprint, url_prefix="/admin")
    login_manager.login_view = "main.render_login"
    main_blueprint.config = application.config.copy()

    @application.before_request
    def remove_trailing_slash():
        if request.path != "/" and request.path.endswith("/"):
            return redirect(request.path[:-1], code=301)

    @application.template_filter("markdown")
    def markdown_filter(data):
        return Markup(markdown(data))

    application.add_template_filter(parse_document_upload_time)

    return application
def create_manager(deed_api_client=make_deed_api_client()):
    app = Flask(__name__)
    app.config.from_pyfile("config.py")

    manager = Manager(app)
    app.url_map.strict_slashes = False

    setattr(searchdeed, "deed_api_client", deed_api_client)

    app.register_blueprint(health, url_prefix="/health")
    app.register_blueprint(searchdeed)
    app.register_blueprint(borrower_landing)
    app.secret_key = app.config["APP_SECRET_KEY"]

    app.permanent_session_lifetime = timedelta(minutes=20)

    return manager
Example #10
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object("config")
    bootstrap.init_app(app)
    # moment.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    app.permanent_session_lifetime = timedelta(hours=24)

    from .main import main as main_blueprint

    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint

    app.register_blueprint(auth_blueprint)

    return app
    def setUp(self):
        application = Flask(__name__)
        application.config["TESTING"] = True
        application.secret_key = "you will not guess"
        application.permanent_session_lifetime = timedelta(seconds=1)

        login_manager.init_app(application)
        self.application = application
        with self.application.test_client() as c:
            with c.session_transaction() as sess:
                sess["user_id"] = "1"

        schema_file = open(os.path.join(settings.EQ_SCHEMA_DIRECTORY, "0_star_wars.json"))
        schema = schema_file.read()
        # create a parser
        self.schema_json = json.loads(schema)
        parser = SchemaParserFactory.create_parser(self.schema_json)
        self.questionnaire = parser.parse()
def create_app(config_name):

    application = Flask(__name__, static_folder="static/", static_url_path=configs[config_name].STATIC_URL_PATH)

    init_app(
        application,
        configs[config_name],
        bootstrap=bootstrap,
        data_api_client=data_api_client,
        feature_flags=feature_flags,
        login_manager=login_manager,
    )
    # Should be incorporated into digitalmarketplace-utils as well
    csrf.init_app(application)

    application.permanent_session_lifetime = timedelta(hours=1)
    from .main import main as main_blueprint
    from .status import status as status_blueprint

    application.register_blueprint(status_blueprint, url_prefix="/admin")
    application.register_blueprint(main_blueprint, url_prefix="/admin")
    login_manager.login_view = "main.render_login"
    main_blueprint.config = application.config.copy()

    @application.before_request
    def remove_trailing_slash():
        if request.path != "/" and request.path.endswith("/"):
            return redirect(request.path[:-1], code=301)

    @application.template_filter("timeformat")
    def timeformat(value):
        return datetime.strptime(value, formats.DATETIME_FORMAT).strftime(DISPLAY_TIME_FORMAT)

    @application.template_filter("dateformat")
    def dateformat(value):
        return datetime.strptime(value, formats.DATETIME_FORMAT).strftime(DISPLAY_DATE_FORMAT)

    @application.template_filter("displaydateformat")
    def display_date_format(value):
        return value.strftime(DISPLAY_DATE_FORMAT)

    return application
Example #13
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    db.init_app(app)
    bootstrap.init_app(app)
    mail.init_app(app)
    login_manager.init_app(app)

    # security setting
    app.secret_key = "youdon'tknwhatIT1s"
    app.permanent_session_lifetime = datetime.timedelta(minutes=30)

    # register blueprint
    from .main import main as main_blueprint

    app.register_blueprint(main_blueprint)

    return app
def create_app(config=config.dev_config, school_name=None):
    """ The main entry point where the application is created """
    # Create the application
    app = Flask(__name__)
    # User only logged in for 10 minutes before getting auto logged out
    app.permanent_session_lifetime = timedelta(seconds=600)
    # Default configurations
    app.config.from_object(config)
    # Configuration overrides
    app.config.from_pyfile("../application.cfg", silent=True)
    # In "multi-school" mode, each school is run as a separate app.
    # And each is run under the root directory (eg. domain.net/school)
    if school_name is not None:
        app.config["SCRIPT_NAME"] = "/" + school_name
    app.config["SCHOOL"] = school_name or app.config["DEFAULT_SCHOOL"]

    # Register everything
    register_extensions(app)
    register_views(app)
    register_template_filters(app)
    configure_hooks(app)
    return app
Example #15
0
def create_app(db_name=None):
    app = Flask(__name__)
    app.config.from_object(config)
    if db_name:
        config.MONGO_DATABASE = db_name

    Admin(app)
    Engine(app)
    mongo, db = HapPyMongo(config)
    app.permanent_session_lifetime = timedelta(hours=2)
    auth = CloudAuth(app, db)

    custom_filters = {name: function for name, function in getmembers(template_filters) if isfunction(function)}
    app.jinja_env.filters.update(custom_filters)
    app.context_processor(template_functions.utility_processor)

    @app.before_first_request
    def logger():
        if not app.debug:
            app.logger.addHandler(logging.StreamHandler())
            app.logger.setLevel(logging.INFO)

    @app.before_request
    def before_request():
        g.db, g.auth = db, auth

    defaults.application_initialize(db, app)
    views.ProductsView.register(app)
    views.MiscView.register(app)
    views.FeedbackView.register(app)
    views.GlobalManageView.register(app)

    if db_name:
        return app, db
    else:
        return app
Example #16
0
# coding:utf-8
from flask import Flask, request, make_response, url_for, render_template, session
from flask.ext.sqlalchemy import SQLAlchemy
from os import urandom
import hashlib

# app = Flask(__name__,static_url_path="/statics")
# so we can use static_url_path to define static file path instead useing the default value
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://bob:123456@localhost/bob"
app.permanent_session_lifetime = 30  # 设置session的超时时间
app.secret_key = urandom(20)
db = SQLAlchemy(app)

# 这个导入必须在db的后面导入,因为models.py中需要导入db。如果在db之前导入,那时候db还未定义,会出错
from models import User


@app.route("/", methods=["GET"])
def index():
    return render_template("index.html")


def hello():
    return "Another hello world"


app.add_url_rule("/index", endpoint="hello", view_func=hello)
# app.add_url_rule():the first arg is the url,and the third arg is the view function
# endpoint is the function which was requested by the client
# coding: utf8
import os
from datetime import timedelta
from flask import Flask, session, render_template, request, redirect
import urllib

app = Flask(__name__)

app.secret_key = os.urandom(24)
app.permanent_session_lifetime = timedelta(seconds=30 * 24 * 60 * 60)


@app.route("/")
def toindex():
    return "nima"


@app.route("/login")
def login():
    session.permanent = True
    referer = request.args.get("referer", None)
    if referer is not None:
        referer = referer.strip()
    if "name" in session:
        if referer is not None:
            return redirect(referer + "?ticket=" + _makeTicket())
    return render_template("login.html", **dict(referer=referer))


@app.route("/dologin")
def doLogin():
Example #18
0
# server config
app.config["SERVER_NAME"] = CONFIG["SERVER_NAME"]
app.config["CSRF_ENABLED"] = True
app.config["SECRET_KEY"] = os.urandom(24)

# gen basic auth
CONFIG["BASIC_AUTH"] = "Basic %s" % base64.encodestring("%s:%s" % (CONFIG["NAME"], CONFIG["PASSWORD"]))[:-1]

# session config
if "REDIS_SESSION" in CONFIG:
    r = redis.Redis(
        host=CONFIG["REDIS_SESSION"]["host"],
        port=CONFIG["REDIS_SESSION"]["port"],
        password=CONFIG["REDIS_SESSION"]["pass"],
    )
    app.permanent_session_lifetime = datetime.timedelta(days=365)
    app.session_interface = RedisSessionInterface(r)
    app.config["CACHE_TYPE"] = "redis"
    app.config["CACHE_REDIS_HOST"] = r
    app.config["CACHE_KEY_PREFIX"] = "cache:"
    # app.config['CACHE_REDIS_DB'] = 1
    cache.init_app(app)

# log config
app.level = DEBUG if ENV == "develop" else INFO
handler_list = []
if "REDIS_LOG" in CONFIG:
    handler = RedisHandler.get_instance(
        "web", CONFIG["REDIS_LOG"]["host"], CONFIG["REDIS_LOG"]["port"], CONFIG["REDIS_LOG"]["pass"]
    )
    handler_list.append(handler)
Example #19
0
from datetime import timedelta
from apscheduler.scheduler import Scheduler

from werkzeug.contrib.fixers import ProxyFix
from flask import Flask
from flask import jsonify

from conf.base import Base
from conf.boostrap import Bootstrap
from services.user_data_service import UserDataService

CONFIG_TYPE = "ProductionConfig"
APP = Flask(__name__)
APP.config.from_object("conf.config.%s" % CONFIG_TYPE)
APP.secret_key = getRandomInteger(128)
APP.permanent_session_lifetime = timedelta(seconds=10)
# Imports all controllers and register pages
CONTROLLERS = []
for controller in os.listdir(os.getcwd() + "/controllers"):
    module_name, ext = os.path.splitext(controller)
    if module_name.endswith("_controller") and ext == ".py":
        module = __import__("controllers.%s" % module_name)
        CONTROLLERS.append(module.__getattribute__(module_name))
for controller in CONTROLLERS:
    APP.register_blueprint(controller.PAGE)

logging.basicConfig(
    filename=APP.config["LOGFILE"],
    level=logging.INFO,
    format="%(asctime)s %(levelname)s: %(message)s " "[in %(pathname)s:%(lineno)d]",
)
Example #20
0
# Load configuration from the environment
secret_key = os.environ.get("SECRET_KEY")
signing_key = os.environ.get("SIGNING_KEY")
if not secret_key:
    raise Exception("SECRET_KEY not set")
if not signing_key:
    raise Exception("SIGNING_KEY not set")

app.config["SERVER_NAME"] = os.environ.get("SERVER_NAME")
app.config["SECRET_KEY"] = secret_key
app.config["BOT_NAME"] = "edsgar"
app.config["SESSION_LIFETIME_DAYS"] = 90  # Used in a template

tokenizer = Tokenizer(signing_key)

app.permanent_session_lifetime = timedelta(days=app.config["SESSION_LIFETIME_DAYS"])


@app.before_request
def before_request():
    session.permanent = True


# This is needed because of a stupid, old bug in Flask
@app.errorhandler(400)
@app.errorhandler(401)
@app.errorhandler(404)
@app.errorhandler(429)
@app.errorhandler(500)
@app.errorhandler(Exception)
def show_error_page(error):
Example #21
0
File: app.py Project: kiennt/jupo
from helpers import extensions
from helpers.converters import SnowflakeIDConverter, RegexConverter, UUIDConverter

import api
import urllib
import filters
import settings


CURRENT_APP = Flask(__name__, static_folder="public", template_folder="templates")


# sslify = SSLify(CURRENT_APP)

CURRENT_APP.secret_key = settings.SECRET_KEY
CURRENT_APP.permanent_session_lifetime = timedelta(days=365 * 10)


# ===============================================================================
# Template settings
# ===============================================================================

CURRENT_APP.jinja_env.add_extension(extensions.FragmentCacheExtension)
CURRENT_APP.jinja_env.fragment_cache = MemcachedCache(servers=settings.MEMCACHED_SERVERS, default_timeout=3600)

CURRENT_APP.jinja_env.filters["split"] = filters.split
CURRENT_APP.jinja_env.filters["clean"] = filters.clean
CURRENT_APP.jinja_env.filters["title"] = filters.title
CURRENT_APP.jinja_env.filters["nl2br"] = filters.nl2br
CURRENT_APP.jinja_env.filters["exclude"] = filters.exclude
CURRENT_APP.jinja_env.filters["unmunge"] = filters.unmunge
Example #22
0
    if html_body is not None:
        msg.html = html_body

    if text_body is not None and html_body is not None:
        thr = Thread(target=send_async_email, args=[app, msg])
        thr.start()


# TODO: LOGGING
# logging.basicConfig(filename='twoweeks.log',level=logging.DEBUG)


##################
# AUTHENTICATION #
##################
app.permanent_session_lifetime = timedelta(minutes=config.PERMANENT_SESSION_LIFETIME)
from werkzeug.security import generate_password_hash

from flask.ext.login import LoginManager, login_user, logout_user, login_required
import base64

login_manager = LoginManager()
login_manager.init_app(app)


@login_manager.user_loader
def load_user(user_id):
    return User.query.filter_by(id=user_id).first()


@app.route("/login")
Example #23
0
from flask import Flask
import datetime

# Create Flask application.
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///memory"
app.permanent_session_lifetime = datetime.timedelta(minutes=10)

# Import and set the session key.
import key

app.secret_key = key.secret

# Import SQLAlchemy and initialize the database object.
from flaskext.sqlalchemy import SQLAlchemy

db = SQLAlchemy(app)

# Run the scheduler.
from eh.helpers.scheduler import HaikuScheduler

sched = HaikuScheduler()
sched.start()

# Import application assets.
from eh.views import admin
Example #24
0
Note: setting these variables through the local environment & using os.environ to access them is preferred for security reasons
"""
app.config["MAIL_SERVER"] = ""
app.config["MAIL_PORT"] = ""
app.config["MAIL_USE_TLS"] = True
app.config["MAIL_USERNAME"] = "test@test.com"
app.config["MAIL_PASSWORD"] = "testpw"

app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + os.path.join(basedir, "data.sqlite")
# app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
# uncomment this line if you want to use Heroku, comment instead the one before it
app.config["SQLALCHEMY_COMMIT_ON_TEARDOWN"] = True

app.config["UPLOAD_FOLDER"] = "./static/balls"

app.permanent_session_lifetime = timedelta(seconds=60)
app.config["SECRET_KEY"] = "veryhard2guess"
# be more original

FTP_USER = "222"
FTP_PASS = "333"
FTP_HOST = "ftp.ftp.com"
# again, environmental variables are preferred
manager = Manager(app)
bootstrap = Bootstrap(app)
db = SQLAlchemy(app)
mail = Mail(app)
db.drop_all()


login_manager = LoginManager()
Example #25
0
from time import time
from datetime import timedelta
from random import random
from urlparse import urlparse
import json

import env_config as config
from fingerprint import FingerprintAgent, FingerprintRecorder, FingerprintHelper
from tracking import TrackingRecorder
from entropy_helper import EntropyHelper
from util import number_format, detect_browser_and_platform, get_tool_recommendation

app = Flask(__name__)
app.secret_key = config.secret_key
app.debug = config.debug
app.permanent_session_lifetime = timedelta(days=config.session_lifetime)
Bower(app)

if config.sentry_dsn:
    app.config["SENTRY_DSN"] = config.sentry_dsn
    sentry = Sentry(app)

with open(config.keyfile, "r") as fp:
    key = fp.read(16)


@app.before_request
def set_cookie():
    session.permanent = True
    # set a long-lived session cookie.  this helps to determine if we've
    # already recorded your fingerprint in the database
Example #26
0
from flask import Flask

app = Flask(__name__)

import CASClient, chat, main, database, authentication, users

from datetime import timedelta

# used for sessions
app.secret_key = "J\"JOx[Lq'.jt7P.qT5i'"
app.permanent_session_lifetime = timedelta(14)
app.session_cookie_name = "ISTREET_SESSION"
app.session_cookie_domain = "istreetsvr.heroku.com"
Example #27
0
import sys
import os
from datetime import timedelta

abspath = os.path.abspath(__file__)
app_root = os.path.dirname(abspath)
# path = os.path.join(app_root, 'lib/python2.7/site-packages')
# sys.path.insert(0, path)
# sys.path.insert(0, app_root)
# sys.path.insert(0, '/home/tianjie/pyworkspace/bteditor/lib')
# sys.path.insert(0, app_root)
from flask import Flask, session
from flask_session import Session

app = Flask(__name__)

reload(sys)
sys.setdefaultencoding("utf-8")
app.config["SESSION_TYPE"] = "kvdb"
Session(app)

session.permanent = True
app.permanent_session_lifetime = timedelta(minutes=5)

from bteditor.controller import *

# app.add_url_rule('/', view_func=index)

if __name__ == "__main__":
    # app.run()
    app.run(debug=True)
Example #28
0
LOG_PATH = "/".join((os.path.dirname(os.path.realpath(__file__)), "log"))
if not os.path.exists(LOG_PATH):
    os.makedirs(LOG_PATH)

handler = RotatingFileHandler(LOG_PATH + "/debug.log", maxBytes=10000, backupCount=1)
handler.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
#### initial logger ####


#### initial sesion ####
from datetime import timedelta

app.config["SECRET_KEY"] = "random"
app.permanent_session_lifetime = timedelta(seconds=60 * 60 * 10)  # session expire time
#### initial sesion ####


#### initial database ####
app.config.from_pyfile("config/database.cfg")
db.init_app(app)
#### initial database ####


#### router ####
from werkzeug.routing import Rule

urlpatterns = {Rule("/", endpoint="index")}

for rule in urlpatterns:
Example #29
0
# -*- coding: utf-8 -*-

import logging

logging.basicConfig(format="[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d] %(message)s")

from datetime import timedelta

from flask import Flask

from zhinsta.settings import SECRET_KEY

app = Flask(__name__)
app.secret_key = SECRET_KEY
app.permanent_session_lifetime = timedelta(days=30)


def run():
    app.run(debug=True)
Example #30
0
    password = request.form["password"]
    loginresult = Login.login(url, username, password)

    if loginresult.result:
        loginCookie = Cookie.SimpleCookie().load(loginresult.cookie)
        print "LOGIN COOKIE: ", loginCookie
        userSession = UserSession(username, url, loginresult.cookie)
        session[sessionKey] = userSession.to_JSON()
        session.permanent = True
        return timbrature()
    else:
        return render_template("pymbrum.html", action="login", message=loginresult.message)


@app.route("/logout")
def logout():
    session.pop(sessionKey, None)
    return render_template("pymbrum.html")


@app.route("/thebot/test", methods=["POST", "GET"])
def the_bot_test():
    bot = telepot.Bot("120630437:AAF9Qo-mJQWQAQCmpOpLbPuNHFvVG-9Ep0U")
    return bot.getMe()


if __name__ == "__main__":
    app.debug = True
    app.secret_key = "A0Zr98j/3yX R~XHH!jmN]LWX/,?RT"
    app.permanent_session_lifetime = timedelta(hours=1)
    app.run()