U a~@sddlZddlZddlZddlZddlZddlmZddl m Z ddl m Z ddl m Z ddlmZddlmZddlmZd d lmZd d lmZd d lmZd d lmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlm Z d dlm!Z!d dlm"Z"d dlm#Z#d dlm$Z$ej%r8d dl&m'Z'e(Z)ej*dej+dej,fdZ-e-e-dddZ.Gdd d Z/ej+e0d!d"d#Z1d$d%Z2d&d'Z3e0d(d)d*Z4dS)+N) defaultdict)update_wrapper) JSONDecoder) JSONEncoder)FileSystemLoader)default_exceptions) HTTPException)AppGroup) current_app) get_root_path)locked_cached_property)send_from_directory)_default_template_ctx_processor)AfterRequestCallable)AppOrBlueprintKey)BeforeRequestCallableErrorHandlerCallable)TeardownCallable) TemplateContextProcessorCallable)URLDefaultCallable)URLValuePreprocessorCallable)ResponseF.)boundfreturncs.tjtjtjdfdd }ttt|S)zkWraps a method so that it performs a check in debug mode if the first request was already handled. )argskwargsrcs |rtd|f||S)NamA setup function was called after the first request was handled. This usually indicates a bug in the application where a module was not imported and decorators or other functionality was called too late. To fix this make sure to import all your view modules, database models, and everything related at a central place before the application starts serving requests.)_is_setup_finishedAssertionError)selfrr rOC:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-e702oxwa\flask\scaffold.py wrapper_func,s  z!setupmethod..wrapper_func)tAnycastrr)rr'r%r$r& setupmethod'sr+c @s|eZdZUdZeed<dZejeed<dZ ejeed<dZ ejej e ed<dZ ejej eed<dQeejeejeejeejedd d Zed d d Zed ddZeejed ddZejejeddddZeed ddZeejed ddZejejeddddZejeejedddZeddddZeejed dd ZdReeejejd"d#d$Z eee!ej"d%d&d'Z#eej$ej"d(d)d*Z%eej$ej"d(d+d,Z&eej$ej"d(d-d.Z'eej$ej"d(d/d0Z(eej$ej"d(d1d2Z)eej$ej"d(d3d4Z*e+dSeejeejej"ejeej$dd5d6d7Z,eej"d8d9d:Z-e+e.e.d;dd?Z1e+e2e2d;d@dAZ3e+e4e4d;dBdCZ5e+e6e6d;dDdEZ7e+e8e8d;dFdGZ9e+ej:ej e;efej"ee?ej:ej e;efej@ej e;ejefdNdOdPZAdS)TScaffoldaCommon behavior shared between :class:`~flask.Flask` and :class:`~flask.blueprints.Blueprint`. :param import_name: The import name of the module where this object is defined. Usually :attr:`__name__` should be used. :param static_folder: Path to a folder of static files to serve. If this is set, a static route will be added. :param static_url_path: URL prefix for the static route. :param template_folder: Path to a folder containing template files. for rendering. If this is set, a Jinja loader will be added. :param root_path: The path that static, template, and resource files are relative to. Typically not set, it is discovered based on the ``import_name``. .. versionadded:: 2.0 nameN_static_folder_static_url_path json_encoder json_decoder) import_name static_folderstatic_url_pathtemplate_folder root_pathcCs||_||_||_||_|dkr*t|j}||_t|_i|_t dd|_ t t |_ t t |_ t t |_t t dtgi|_t t |_t t |_dS)NcSsttSN)rdictr%r%r%r&z#Scaffold.__init__..)r2r3r4r5r r6r cliview_functionsrerror_handler_speclistbefore_request_funcsafter_request_funcsteardown_request_funcsrtemplate_context_processorsurl_value_preprocessorsurl_default_functions)r#r2r3r4r5r6r%r%r&__init__[s.   zScaffold.__init__)rcCsdt|jd|jdS)N< >)type__name__r-r#r%r%r&__repr__szScaffold.__repr__cCstdSr7NotImplementedErrorrKr%r%r&r!szScaffold._is_setup_finishedcCs$|jdk rtj|j|jSdSdS)zhThe absolute path to the configured static folder. ``None`` if no static folder is set. N)r.ospathjoinr6rKr%r%r&r3s zScaffold.static_folder)valuercCs"|dk rt|d}||_dS)Nz\/)rOfspathrstripr.r#rRr%r%r&r3scCs |jdk S)zQ``True`` if :attr:`static_folder` is set. .. versionadded:: 0.5 N)r3rKr%r%r&has_static_folderszScaffold.has_static_foldercCs<|jdk r|jS|jdk r8tj|j}d|dSdS)zThe URL prefix that the static route will be accessible from. If it was not configured during init, it is derived from :attr:`static_folder`. N/)r/r3rOrPbasenamerT)r#rXr%r%r&r4s   zScaffold.static_url_pathcCs|dk r|d}||_dS)NrW)rTr/rUr%r%r&r4s )filenamercCstj}|dkrdSt|S)aUsed by :func:`send_file` to determine the ``max_age`` cache value for a given file path if it wasn't passed. By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from the configuration of :data:`~flask.current_app`. This defaults to ``None``, which tells the browser to use conditional requests instead of a timed cache, which is usually preferable. .. versionchanged:: 2.0 The default configuration is ``None`` instead of 12 hours. .. versionadded:: 0.9 N)r Zsend_file_max_age_defaultint total_seconds)r#rYrRr%r%r&get_send_file_max_age%szScaffold.get_send_file_max_agercCs0|jstd||}ttt|j||dS)zThe view function used to serve files from :attr:`static_folder`. A route is automatically registered for this view at :attr:`static_url_path` if :attr:`static_folder` is set. .. versionadded:: 0.5 z2'static_folder' must be set to serve static_files.)max_age)rV RuntimeErrorr\rr(r*strr3)r#rYr]r%r%r&send_static_file:s  zScaffold.send_static_filecCs(|jdk r ttj|j|jSdSdS)zThe Jinja loader for this object's templates. By default this is a class :class:`jinja2.loaders.FileSystemLoader` to :attr:`template_folder` if it is set. .. versionadded:: 0.5 N)r5rrOrPrQr6rKr%r%r& jinja_loaderLs zScaffold.jinja_loaderrb)resourcemodercCs&|dkrtdttj|j||S)aKOpen a resource file relative to :attr:`root_path` for reading. For example, if the file ``schema.sql`` is next to the file ``app.py`` where the ``Flask`` app is defined, it can be opened with: .. code-block:: python with app.open_resource("schema.sql") as f: conn.executescript(f.read()) :param resource: Path to the resource relative to :attr:`root_path`. :param mode: Open the file in this mode. Only reading is supported, valid values are "r" (or "rt") and "rb". >rtrbrz)Resources can only be opened for reading.) ValueErroropenrOrPrQr6)r#rcrdr%r%r& open_resourceYszScaffold.open_resource)methodruleoptionsrcCs(d|krtd|j|fd|gi|S)Nmethodsz8Use the 'route' decorator to use the 'methods' argument.) TypeErrorroute)r#rjrkrlr%r%r& _method_routepszScaffold._method_route)rkrlrcKs|d||S)z\Shortcut for :meth:`route` with ``methods=["GET"]``. .. versionadded:: 2.0 GETrpr#rkrlr%r%r&getvsz Scaffold.getcKs|d||S)z]Shortcut for :meth:`route` with ``methods=["POST"]``. .. versionadded:: 2.0 POSTrrrsr%r%r&post}sz Scaffold.postcKs|d||S)z\Shortcut for :meth:`route` with ``methods=["PUT"]``. .. versionadded:: 2.0 PUTrrrsr%r%r&putsz Scaffold.putcKs|d||S)z_Shortcut for :meth:`route` with ``methods=["DELETE"]``. .. versionadded:: 2.0 DELETErrrsr%r%r&deleteszScaffold.deletecKs|d||S)z^Shortcut for :meth:`route` with ``methods=["PATCH"]``. .. versionadded:: 2.0 PATCHrrrsr%r%r&patchszScaffold.patchc s tjtjdfdd }|S)aDecorate a view function to register it with the given URL rule and options. Calls :meth:`add_url_rule`, which has more details about the implementation. .. code-block:: python @app.route("/") def index(): return "Hello, World!" See :ref:`url-route-registrations`. The endpoint name for the route defaults to the name of the view function if the ``endpoint`` parameter isn't passed. The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and ``OPTIONS`` are added automatically. :param rule: The URL rule string. :param options: Extra options passed to the :class:`~werkzeug.routing.Rule` object. rcs"dd}j||f|S)Nendpoint)pop add_url_rule)rr}rlrkr#r%r& decorators z!Scaffold.route..decorator)r(Callable)r#rkrlrr%rr&roszScaffold.route)rkr} view_funcprovide_automatic_optionsrlrcKstdS)a;Register a rule for routing incoming requests and building URLs. The :meth:`route` decorator is a shortcut to call this with the ``view_func`` argument. These are equivalent: .. code-block:: python @app.route("/") def index(): ... .. code-block:: python def index(): ... app.add_url_rule("/", view_func=index) See :ref:`url-route-registrations`. The endpoint name for the route defaults to the name of the view function if the ``endpoint`` parameter isn't passed. An error will be raised if a function has already been registered for the endpoint. The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` is always added automatically, and ``OPTIONS`` is added automatically by default. ``view_func`` does not necessarily need to be passed, but if the rule should participate in routing an endpoint name must be associated with a view function at some point with the :meth:`endpoint` decorator. .. code-block:: python app.add_url_rule("/", endpoint="index") @app.endpoint("index") def index(): ... If ``view_func`` has a ``required_methods`` attribute, those methods are added to the passed and automatic methods. If it has a ``provide_automatic_methods`` attribute, it is used as the default if the parameter is not passed. :param rule: The URL rule string. :param endpoint: The endpoint name to associate with the rule and view function. Used when routing and building URLs. Defaults to ``view_func.__name__``. :param view_func: The view function to associate with the endpoint name. :param provide_automatic_options: Add the ``OPTIONS`` method and respond to ``OPTIONS`` requests automatically. :param options: Extra options passed to the :class:`~werkzeug.routing.Rule` object. NrM)r#rkr}rrrlr%r%r&rsBzScaffold.add_url_rule)r}rcsfdd}|S)aDecorate a view function to register it for the given endpoint. Used if a rule is added without a ``view_func`` with :meth:`add_url_rule`. .. code-block:: python app.add_url_rule("/ex", endpoint="example") @app.endpoint("example") def example(): ... :param endpoint: The endpoint name to associate with the view function. cs|j<|Sr7)r<r$r}r#r%r&r s z$Scaffold.endpoint..decoratorr%)r#r}rr%rr&r}szScaffold.endpointrcCs|jdg||S)a`Register a function to run before each request. For example, this can be used to open a database connection, or to load the logged in user from the session. .. code-block:: python @app.before_request def load_user(): if "user_id" in session: g.user = db.session.get(session["user_id"]) The function will be called without any arguments. If it returns a non-``None`` value, the value is handled as if it was the return value from the view, and further request handling is stopped. N)r? setdefaultappendr#rr%r%r&before_requestszScaffold.before_requestcCs|jdg||S)a Register a function to run after each request to this object. The function is called with the response object, and must return a response object. This allows the functions to modify or replace the response before it is sent. If a function raises an exception, any remaining ``after_request`` functions will not be called. Therefore, this should not be used for actions that must execute, such as to close resources. Use :meth:`teardown_request` for that. N)r@rrrr%r%r& after_request)s zScaffold.after_requestcCs|jdg||S)arRegister a function to be run at the end of each request, regardless of whether there was an exception or not. These functions are executed when the request context is popped, even if not an actual request was performed. Example:: ctx = app.test_request_context() ctx.push() ... ctx.pop() When ``ctx.pop()`` is executed in the above example, the teardown functions are called just before the request context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests. Teardown functions must avoid raising exceptions, since they . If they execute code that might fail they will have to surround the execution of these code by try/except statements and log occurring errors. When a teardown function was called because of an exception it will be passed an error object. The return values of teardown functions are ignored. .. admonition:: Debug Note In debug mode Flask will not tear down a request on an exception immediately. Instead it will keep it alive so that the interactive debugger can still access it. This behavior can be controlled by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable. N)rArrrr%r%r&teardown_request9s$zScaffold.teardown_requestcCs|jd||S)z0Registers a template context processor function.N)rBrrr%r%r&context_processor`szScaffold.context_processorcCs|jd||S)a#Register a URL value preprocessor function for all view functions in the application. These functions will be called before the :meth:`before_request` functions. The function can modify the values captured from the matched url before they are passed to the view. For example, this can be used to pop a common language code value and place it in ``g`` rather than pass it to every view. The function is passed the endpoint name and values dict. The return value is ignored. N)rCrrr%r%r&url_value_preprocessorhszScaffold.url_value_preprocessorcCs|jd||S)zCallback function for URL defaults for all view functions of the application. It's called with the endpoint and values and should update the values passed in place. N)rDrrr%r%r& url_defaults{szScaffold.url_defaults)code_or_exceptionrcsttdfdd }|S)a7Register a function to handle errors by code or exception class. A decorator that is used to register a function given an error code. Example:: @app.errorhandler(404) def page_not_found(error): return 'This page does not exist', 404 You can also register handlers for arbitrary exceptions:: @app.errorhandler(DatabaseError) def special_exception_handler(error): return 'Database connection failed', 500 .. versionadded:: 0.7 Use :meth:`register_error_handler` instead of modifying :attr:`error_handler_spec` directly, for application wide error handlers. .. versionadded:: 0.7 One can now additionally also register custom exception types that do not necessarily have to be a subclass of the :class:`~werkzeug.exceptions.HTTPException` class. :param code_or_exception: the code as integer for the handler, or an arbitrary exception rcs||Sr7)register_error_handlerr$rr#r%r&rs z(Scaffold.errorhandler..decoratorr)r#rrr%rr& errorhandlers!zScaffold.errorhandler)rrrcCsht|trtd|dz||\}}Wn$tk rPtd|dYnX||jd||<dS)zAlternative error attach function to the :meth:`errorhandler` decorator that is more straightforward to use for non decorator usage. .. versionadded:: 0.7 z6Tried to register a handler for an exception instance zL. Handlers can only be registered for exception classes or HTTP error codes.'z^' is not a recognized HTTP error code. Use a subclass of HTTPException with that code instead.N) isinstancerrg_get_exc_class_and_codeKeyErrorr=)r#rr exc_classcoder%r%r&rs   zScaffold.register_error_handler)exc_class_or_codercCsJt|trt|}n|}t|ts*tdt|tr>||jfS|dfSdS)a Get the exception class being handled. For HTTP status codes or ``HTTPException`` subclasses, return both the exception and status code. :param exc_class_or_code: Any exception class, or an HTTP status code as an integer. z2Custom exceptions must be subclasses of Exception.N)rrZr issubclass Exceptionr"rr)rrr%r%r&rs    z Scaffold._get_exc_class_and_code)NNNN)rb)NNN)BrJ __module__ __qualname____doc__r___annotations__r.r(Optionalr/r0Typerr1rrErLboolr!propertyr3setterrVr4rZr\r`r rraIOAnyStrrir8rrpr)rtrvrxrzr|ror+rr}rrrrrrrrrrrrUnionrrrr staticmethodTuplerr%r%r%r&r,=s     C&&r,)rrcCs|dk std|jS)zsInternal helper that returns the default endpoint for a given function. This always is the function name. Nz/expected view func if endpoint is not provided.)r"rJ)rr%r%r&_endpoint_from_view_funcsrcCsJt|dr||St|}|jdkr4|jdkr4dStd|jddS)zAttempt to figure out if the given name is a package or a module. :param: loader: The loader that handled the name. :param mod_name: The name of the package or module. is_package_frozen_importlibZNamespaceLoaderTrz<.is_package()' must be implemented for PEP 302 import hooks.N)hasattrrrIrrJAttributeError)loadermod_nameclsr%r%r&)_matching_loader_thinks_module_is_packages   rc Cs z tj|}|dkrtdWnttfk r8YnLX|jdkrZtjt t |j S|j rvtjtj|jStj|jSt |}|dks|dkrtSt|dr||}nt|dr|j}n t|j}tjtj|}t||rtj|}|S)z2Find the path that contains the package or module.Nz not found>N namespace__main__ get_filenamearchive) importlibutil find_specrg ImportErrororiginrOrPdirnamenextitersubmodule_search_locationspkgutil get_loadergetcwdrrr import_module__file__abspathr) root_mod_namespecrrY package_pathr%r%r&_find_package_paths.          r)r2c Cs|d\}}}t|}tjtj}||r8||fStj|\}}| dkrtj|\}}| dkrx||fStj | dkrtj ||fS||fSd|fS)aFind the prefix that a package is installed under, and the path that it would be imported from. The prefix is the directory containing the standard directory hierarchy (lib, bin, etc.). If the package is not installed to the system (:attr:`sys.prefix`) or a virtualenv (``site-packages``), ``None`` is returned. The path is the entry in :attr:`sys.path` that contains the package for import. If the package is not installed, it's assumed that the package was imported from the current working directory. .z site-packageslibN) partitionrrOrPrsysprefix startswithsplitlowerrXr) r2r_rZ py_prefixZ site_parentZ site_folderparentfolderr%r%r& find_package9s    r)5importlib.utilrrOrrtypingr( collectionsr functoolsrjsonrrZjinja2rZwerkzeug.exceptionsrrr;r globalsr Zhelpersr r rZ templatingrrrrrrrrr TYPE_CHECKINGwrappersrobject _sentinelTypeVarrr)rr+r,r_rrrrr%r%r%r&sP                      ,4