示例#1
0
def make_middleware(wrapped, **args):
    """
    Make middleware wsgi app
    """
    _LOG.debug('Middleware function arguments is %r', args)
    local_manager = LocalManager([NoAuth.LOCALS])
    app = NoAuth(wrapped)
    return local_manager.make_middleware(app)
示例#2
0
 def __init__(self, database_url: str, **options):
     self._local = Local()
     self._local_manager = LocalManager([self._local])
     self._database_url = database_url
     self._options = options
     self.engine: Engine = self.create_engine()
     self.metadata = MetaData()
     self.session_mkr = sessionmaker(bind=self.engine)
     self.session = self.session_mkr(autocommit=True)  # type: Session
示例#3
0
    def __init__(self, app):
        """Initialize the middleware, and chain it to the given app.

        app (function): a WSGI application.

        """
        self._app = app

        self._local = Local()
        self._local_manager = LocalManager([self._local])
        self.wsgi_app = self._local_manager.make_middleware(self.wsgi_app)

        self._request = self._local("request")
        self._cookie = self._local("cookie")
示例#4
0
def create_application(from_file):
    if from_file:
        work_dir = os.path.dirname(os.path.abspath(from_file))
    else:
        work_dir = os.getcwd()
    os.chdir(work_dir)
    static_files = {'/static': os.path.join(work_dir, 'static')}

    jam.context = Local()
    local_manager = LocalManager([jam.context])

    application = App(work_dir)
    application = SharedDataMiddleware(application, static_files)
    application = local_manager.make_middleware(application)
    return application
示例#5
0
文件: wsgi.py 项目: alucab/jam-py
def create_application(from_file=None, load_task=False, testing=False):
    if from_file:
        if os.path.isfile(from_file):
            work_dir = os.path.dirname(from_file)
        else:
            work_dir = from_file
    else:
        work_dir = os.getcwd()
    work_dir = os.path.realpath(work_dir)
    os.chdir(work_dir)
    static_files = {'/static': os.path.join(work_dir, 'static')}

    jam.context = Local()
    local_manager = LocalManager([jam.context])

    application = App(work_dir, load_task)
    if not testing:
        application = SharedDataMiddleware(application, static_files)
        application = local_manager.make_middleware(application)
    return application
示例#6
0
文件: wsgi.py 项目: jam-py/jam-py
def create_application(from_file=None):
    if from_file:
        if os.path.isfile(from_file):
            work_dir = os.path.dirname(from_file)
        else:
            work_dir = from_file
    else:
        work_dir = os.getcwd()
    work_dir = os.path.realpath(work_dir)
    os.chdir(work_dir)
    static_files = {
        '/static':  os.path.join(work_dir, 'static')
    }

    jam.context = Local()
    local_manager = LocalManager([jam.context])

    application = App(work_dir)
    application = SharedDataMiddleware(application, static_files)
    application = local_manager.make_middleware(application)
    return application
示例#7
0
    def __init__(self, app):
        """Initialize the middleware, and chain it to the given app.

        app (function): a WSGI application.

        """
        self._app = app

        self._local = Local()
        self._local_manager = LocalManager([self._local])
        self.wsgi_app = self._local_manager.make_middleware(self.wsgi_app)

        self._request = self._local("request")
        self._cookie = self._local("cookie")
示例#8
0
    def __init__(self, debug=False):
        # Application.__setattr__ depends on _properties so we need to set it
        # using the parent implementation.  A bit magic
        super(Application, self).__setattr__('_properties', {})
        self._methods = {}

        self.debug = debug

        # reference to the bottom of a stack of wsgi middleware wrapping
        # :method:`_dispatch_request`. Invoked by :method:`__call__`.
        # Essentially the real wsgi application.
        self._stack = self._dispatch_request

        # TODO provide a way of adding request specific variables.  Need to be
        # able to register name, `(Application, wsgi_env) -> value` pairs
        # Alternatively get rid of this entirely as it's a massive hack
        self._local = Local()
        self._wsgi_env = self._local('wsgi_env')
        self._map_adapter = self._local('map_adapter')

        local_manager = LocalManager([self._local])
        self.add_middleware(local_manager.make_middleware)
示例#9
0
sys.path.insert(0, 'lib')

from werkzeug.wrappers import Request, Response
from werkzeug.local import LocalManager
from webnotes.middlewares import StaticDataMiddleware
from werkzeug.exceptions import HTTPException
from werkzeug.contrib.profiler import ProfilerMiddleware
from webnotes import get_config

import mimetypes
import webnotes
import webnotes.handler
import webnotes.auth
import webnotes.webutils

local_manager = LocalManager([webnotes.local])


@Request.application
def application(request):
    webnotes.local.request = request

    try:
        site = webnotes.utils.get_site_name(request.host)
        webnotes.init(site=site)

        webnotes.local.form_dict = webnotes._dict({ k:v[0] if isinstance(v, (list, tuple)) else v \
         for k, v in (request.form or request.args).iteritems() })

        webnotes.local._response = Response()
示例#10
0
def create_app():
    local = Local()
    local_manager = LocalManager([local])
    app = local_manager.make_middleware(Olaf())
    app = set_statics(app)
    return app
示例#11
0
from werkzeug.local import Local, LocalManager

local = Local()
local_manager = LocalManager()

request = local('request')
"""from werkzeug.local import Local, LocalManager

if __name__ == "__main__":
    local = Local()
    #request = LocalProxy(local, 'request')
    request = ('request')
    local_manager = LocalManager([local])
#request = LocalProxy(local, 'request')
#request = LocalManager([local])"""
示例#12
0
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import

from builtins import *  # noqa

from werkzeug.local import Local, LocalManager, release_local

# a per request context. Generally, this will be the equivelant of thread local
# storage, but if greenlets are being used, it will be a greenlet local.
request_context = Local()

# used in wsgi stack for clean up
_manager = LocalManager(request_context)
cleanup_middleware = _manager.make_middleware


def cleanup():
    release_local(request_context)
示例#13
0
class AWSAuthMiddleware(object):
    """Handler for the low-level tasks of admin authentication.

    Intercepts all requests and responses to AWS, parses the auth
    cookie to retrieve the admin, provides an interface for the rest of
    the application to access and modify this information, and then
    writes the headers to update the cookie.

    A single instance of this class manages the cookies for all current
    requests at the same time, using a Local object from Werkzeug.

    """
    COOKIE = "awslogin"

    def __init__(self, app):
        """Initialize the middleware, and chain it to the given app.

        app (function): a WSGI application.

        """
        self._app = app

        self._local = Local()
        self._local_manager = LocalManager([self._local])
        self.wsgi_app = self._local_manager.make_middleware(self.wsgi_app)

        self._request = self._local("request")
        self._cookie = self._local("cookie")

    @property
    def admin_id(self):
        """Return the ID of the admin.

        It's the value that has been read from the cookie and (if
        modified by the rest of the application) will be written back.

        returns (int or None): the ID of the admin, if logged in.

        """
        return self._cookie.get("id", None)

    def set(self, admin_id):
        """Set the admin ID that will be stored in the cookie.

        admin_id (int): the ID of the admin (to unset don't pass None:
            use clear()).

        """
        self._cookie["id"] = admin_id
        self._cookie["ip"] = self._request.remote_addr
        self.refresh()

    def refresh(self):
        """Update the timestamp that will be stored in the cookie.

        """
        self._cookie["timestamp"] = make_timestamp()

    def clear(self):
        """Remove all fields from the cookie.

        This doesn't actually cause the client to remove the cookie, it
        just makes it update the stored cookie to an empty value.

        """
        self._cookie.clear()

    def __call__(self, environ, start_response):
        """Invoke the class as a WSGI application.

        environ (dict): the WSGI environment.
        start_response (function): the WSGI start_response callable.
        returns (iterable): the WSGI response data.

        """
        return self.wsgi_app(environ, start_response)

    def wsgi_app(self, environ, start_response):
        """Invoke the class as a WSGI application.

        environ (dict): the WSGI environment.
        start_response (function): the WSGI start_response callable.
        returns (iterable): the WSGI response data.

        """
        self._local.request = Request(environ)
        self._local.cookie = JSONSecureCookie.load_cookie(
            self._request, AWSAuthMiddleware.COOKIE, config.secret_key)
        self._verify_cookie()

        def my_start_response(status, headers, exc_info=None):
            """Wrapper for the server-provided start_response.

            Once called by the application, modifies the received
            parameters to add the Set-Cookie parameter (if needed)
            and then forwards everything to the server.

            """
            response = Response(status=status, headers=headers)
            self._cookie.save_cookie(
                response, AWSAuthMiddleware.COOKIE, httponly=True)
            return start_response(
                status, response.headers.to_wsgi_list(), exc_info)

        return self._app(environ, my_start_response)

    def _verify_cookie(self):
        """Check whether the cookie is valid, and if not clear it.

        """
        # Clearing an empty cookie marks it as modified and causes it
        # to be sent in the response. This check prevents it.
        if len(self._cookie) == 0:
            return

        admin_id = self._cookie.get("id", None)
        remote_addr = self._cookie.get("ip", None)
        timestamp = self._cookie.get("timestamp", None)

        if admin_id is None or remote_addr is None or timestamp is None:
            self.clear()
            return

        if not isinstance(admin_id, int) or not isinstance(timestamp, float):
            self.clear()
            return

        if remote_addr != self._request.remote_addr:
            self.clear()
            return

        if make_timestamp() - timestamp > config.admin_cookie_duration:
            self.clear()
            return
示例#14
0
class Db:

    def __init__(self, database_url: str, **options):
        self._local = Local()
        self._local_manager = LocalManager([self._local])
        self._database_url = database_url
        self._options = options
        self.engine: Engine = self.create_engine()
        self.metadata = MetaData()
        self.session_mkr = sessionmaker(bind=self.engine)
        self.session = self.session_mkr(autocommit=True)  # type: Session

    def create_engine(self) -> Engine:
        return create_engine(self._database_url, **self._options)

    def connect(self):
        try:
            self._local.connection
        except AttributeError:
            return self._new_connection_context()
        return self._reuse_connection_context()

    @property
    def s(self) -> Session:
        return self.session

    @contextmanager
    def _new_connection_context(self):
        logger.debug('[%s] Getting new connection from pool', self._local_manager.get_ident())
        conn = self.engine.connect()
        self._local.connection = conn
        yield conn
        logger.debug('[%s] Releasing connection to pool', self._local_manager.get_ident())
        self._local.connection = None
        release_local(self._local)
        conn.close()

    @contextmanager
    def _reuse_connection_context(self):
        logger.debug('[%s] Reusing connection', self._local_manager.get_ident())
        yield self._local.connection
        logger.debug('[%s] Finished using connection', self._local_manager.get_ident())

    @contextmanager
    def transaction(self, autocommit=True, rollback=False):
        with self.connect() as conn:
            logger.debug('[%s] Starting transaction', self._local_manager.get_ident())
            trans = conn.begin_nested()
            try:
                yield conn

                if autocommit:
                    logger.debug('[%s] Committing transaction', self._local_manager.get_ident())
                    trans.commit()

                if rollback:
                    logger.debug('[%s] Rolling back transaction', self._local_manager.get_ident())
                    trans.rollback()

            except Exception:
                logger.debug('[%s] Rolling back transaction (exception)',
                             self._local_manager.get_ident())
                trans.rollback()
                raise

    def execute(self, *args, **kwargs) -> ResultProxy:
        with self.connect() as conn:
            return conn.execute(*args, **kwargs)

    def execute_batch(self, records: list) -> None:
        with self.connect() as conn:
            for r in records:
                conn.execute(r)
示例#15
0
文件: app.py 项目: praba230890/frappe
from werkzeug.local import LocalManager
from werkzeug.exceptions import HTTPException, NotFound
from werkzeug.contrib.profiler import ProfilerMiddleware
from werkzeug.wsgi import SharedDataMiddleware

import mimetypes
import frappe
import frappe.handler
import frappe.auth
import frappe.api
import frappe.utils.response
import frappe.website.render
from frappe.utils import get_site_name
from frappe.middlewares import StaticDataMiddleware

local_manager = LocalManager([frappe.local])

_site = None
_sites_path = os.environ.get("SITES_PATH", ".")

logger = frappe.get_logger()

@Request.application
def application(request):
	frappe.local.request = request
	frappe.local.is_ajax = frappe.get_request_header("X-Requested-With")=="XMLHttpRequest"
	response = None

	try:
		rollback = True
示例#16
0
import dataent.api
import dataent.utils.response
import dataent.website.render
from dataent.utils import get_site_name
from dataent.middlewares import StaticDataMiddleware
from dataent.utils.error import make_error_snapshot
from dataent.core.doctype.communication.comment import update_comments_in_parent_after_request
from dataent import _

# imports - third-party imports
import pymysql
from pymysql.constants import ER

# imports - module imports

local_manager = LocalManager([dataent.local])

_site = None
_sites_path = os.environ.get("SITES_PATH", ".")


class RequestContext(object):
    def __init__(self, environ):
        self.request = Request(environ)

    def __enter__(self):
        init_request(self.request)

    def __exit__(self, type, value, traceback):
        dataent.destroy()
示例#17
0
 def configure(self) -> None:
     self._locals = Local()
     self._local_manager = LocalManager([self._locals])
     self.prepare()
示例#18
0
from datetime import datetime, timedelta
import os
import sys

from werkzeug.exceptions import HTTPException, BadRequestKeyError
from werkzeug.local import LocalManager
from werkzeug.serving import run_simple
from werkzeug.utils import import_string

from .config import ShakeSettings
from .routes import Map, Rule
from .helpers import local
from .serializers import to_json
from .wrappers import Request, Response

local_manager = LocalManager([local])
SECRET_KEY_MINLEN = 20
STATIC_DIR = 'static'
WELCOME_MESSAGE = "Welcome aboard. You're now using Shake!"


class Shake(object):
    """Implements a WSGI application and acts as the central
    object.
    
    :param url_map: Sequence of url rules.
    
    :param settings: A module or dict with the custom settings.
    
    Usually you create a :class:Shake instance in your main module or
    in the `__init__.py` file of your package like this::
示例#19
0
from werkzeug.exceptions import abort
from werkzeug.local import Local, LocalManager, LocalProxy
from werkzeug.routing import Map, Rule
from werkzeug.serving import run_simple
from werkzeug.wrappers import Request, Response

from .errors import get_status_code_from_error_code

__all__ = ["Server", "DebuggedJsonRpcApplication", "current_request"]


DEFAULT_API_ENDPOINT_NAME = "/api"

_CURRENT_REQUEST_KEY = "current_request"
_local = Local()  # pylint: disable=invalid-name
_LOCAL_MANAGER = LocalManager([_local])

current_request = LocalProxy(_local, _CURRENT_REQUEST_KEY)  # pylint: disable=invalid-name
"""A thread-local which stores the current request object when dispatching requests for
:class:`Server`.

Stores a :class:`werkzeug.wrappers.Request`.

.. versionadded:: 0.2.0
"""


class Server(object):
    """A basic WSGI-compatible server for typedjsonrpc endpoints.

    :attribute registry: The registry for this server
示例#20
0
 def configure(self):
     self._locals = Local()
     self._local_manager = LocalManager([self._locals])
     self.reset()
示例#21
0
from werkzeug.local import Local, LocalManager

context = Local()
local_manager = LocalManager([context])


def release_context():
    local_manager.cleanup()
示例#22
0
# Soft dependency on Werkzeug
try:
    from werkzeug.local import Local, LocalManager
    from werkzeug.routing import Map, Rule

    local = Local()
    local_manager = LocalManager([local])

except:
    from cubes.common import MissingPackage
    _missing = MissingPackage("werkzeug", "Slicer server")
    Local = LocalManager = _missing
    Map = Rule = _missing

    local = _missing
    local_manager = _missing
示例#23
0
class AWSAuthMiddleware(object):
    """Handler for the low-level tasks of admin authentication.

    Intercepts all requests and responses to AWS, parses the auth
    cookie to retrieve the admin, provides an interface for the rest of
    the application to access and modify this information, and then
    writes the headers to update the cookie.

    A single instance of this class manages the cookies for all current
    requests at the same time, using a Local object from Werkzeug.

    """
    COOKIE = "awslogin"

    def __init__(self, app):
        """Initialize the middleware, and chain it to the given app.

        app (function): a WSGI application.

        """
        self._app = app

        self._local = Local()
        self._local_manager = LocalManager([self._local])
        self.wsgi_app = self._local_manager.make_middleware(self.wsgi_app)

        self._request = self._local("request")
        self._cookie = self._local("cookie")

    @property
    def admin_id(self):
        """Return the ID of the admin.

        It's the value that has been read from the cookie and (if
        modified by the rest of the application) will be written back.

        returns (int or None): the ID of the admin, if logged in.

        """
        return self._cookie.get("id", None)

    def set(self, admin_id):
        """Set the admin ID that will be stored in the cookie.

        admin_id (int): the ID of the admin (to unset don't pass None:
            use clear()).

        """
        self._cookie["id"] = admin_id
        self._cookie["ip"] = self._request.remote_addr
        self.refresh()

    def refresh(self):
        """Update the timestamp that will be stored in the cookie.

        """
        self._cookie["timestamp"] = make_timestamp()

    def clear(self):
        """Remove all fields from the cookie.

        This doesn't actually cause the client to remove the cookie, it
        just makes it update the stored cookie to an empty value.

        """
        self._cookie.clear()

    def __call__(self, environ, start_response):
        """Invoke the class as a WSGI application.

        environ (dict): the WSGI environment.
        start_response (function): the WSGI start_response callable.
        returns (iterable): the WSGI response data.

        """
        return self.wsgi_app(environ, start_response)

    def wsgi_app(self, environ, start_response):
        """Invoke the class as a WSGI application.

        environ (dict): the WSGI environment.
        start_response (function): the WSGI start_response callable.
        returns (iterable): the WSGI response data.

        """
        self._local.request = Request(environ)
        self._local.cookie = JSONSecureCookie.load_cookie(
            self._request, AWSAuthMiddleware.COOKIE,
            hex_to_bin(config.secret_key))
        self._verify_cookie()

        def my_start_response(status, headers, exc_info=None):
            """Wrapper for the server-provided start_response.

            Once called by the application, modifies the received
            parameters to add the Set-Cookie parameter (if needed)
            and then forwards everything to the server.

            """
            response = Response(status=status, headers=headers)
            self._cookie.save_cookie(response,
                                     AWSAuthMiddleware.COOKIE,
                                     httponly=True)
            return start_response(status, response.headers.to_wsgi_list(),
                                  exc_info)

        return self._app(environ, my_start_response)

    def _verify_cookie(self):
        """Check whether the cookie is valid, and if not clear it.

        """
        # Clearing an empty cookie marks it as modified and causes it
        # to be sent in the response. This check prevents it.
        if len(self._cookie) == 0:
            return

        admin_id = self._cookie.get("id", None)
        remote_addr = self._cookie.get("ip", None)
        timestamp = self._cookie.get("timestamp", None)

        if admin_id is None or remote_addr is None or timestamp is None:
            self.clear()
            return

        if not isinstance(admin_id, int) or not isinstance(timestamp, float):
            self.clear()
            return

        if remote_addr != self._request.remote_addr:
            self.clear()
            return

        if make_timestamp() - timestamp > config.admin_cookie_duration:
            self.clear()
            return
示例#24
0
import frappe
import frappe.handler
import frappe.auth
import frappe.api
import frappe.utils.response
import frappe.website.render
from frappe.utils import get_site_name, sanitize_html
from frappe.middlewares import StaticDataMiddleware
from frappe.utils.error import make_error_snapshot
from frappe.core.doctype.comment.comment import update_comments_in_parent_after_request
from frappe import _
import frappe.recorder
import frappe.monitor
import frappe.rate_limiter

local_manager = LocalManager([frappe.local])

_site = None
_sites_path = os.environ.get("SITES_PATH", ".")


class RequestContext(object):
    def __init__(self, environ):
        self.request = Request(environ)

    def __enter__(self):
        init_request(self.request)

    def __exit__(self, type, value, traceback):
        frappe.destroy()
示例#25
0
文件: app.py 项目: ccarruitero/Shake
import os
import sys

from werkzeug.exceptions import HTTPException, BadRequestKeyError
from werkzeug.local import LocalManager
from werkzeug.serving import run_simple
from werkzeug.utils import import_string

from .config import ShakeSettings
from .routes import Map, Rule
from .helpers import local
from .serializers import to_json
from .wrappers import Request, Response


local_manager = LocalManager([local])
SECRET_KEY_MINLEN = 20
STATIC_DIR = 'static'
WELCOME_MESSAGE = "Welcome aboard. You're now using Shake!"


class Shake(object):
    """Implements a WSGI application and acts as the central
    object.
    
    :param url_map: Sequence of url rules.
    
    :param settings: A module or dict with the custom settings.
    
    Usually you create a :class:Shake instance in your main module or
    in the `__init__.py` file of your package like this::