### Project Setup with setup.py Source: https://morepath.readthedocs.io/latest/_sources/organizing_your_project.rst.txt Example setup.py for a Morepath project, declaring dependencies and entry points for console scripts. Ensure your project has a Python package subdirectory with an __init__.py. ```python from setuptools import setup, find_packages setup(name='myproject', packages=find_packages(), install_requires=[ 'morepath' ], entry_points={ 'console_scripts': [ 'myproject-start = myproject.run:run' ] }) ``` -------------------------------- ### Run Morepath Example Source: https://morepath.readthedocs.io/latest/installation.html Executes a Morepath example script using the installed virtual environment. ```bash $ python quickstart.py ``` -------------------------------- ### Namespace Package Setup Source: https://morepath.readthedocs.io/latest/organizing_your_project.html Example setup.py configuration for a project using namespace packages. It specifies the project name, includes all packages, declares the namespace package, lists dependencies, and defines a console script entry point. ```python setup(name='myproject.core', packages=find_packages(), namespace_packages=['myproject'], install_requires=[ 'morepath' ], entry_points={ 'console_scripts': [ 'myproject.core-start = myproject.core.run:run' ] }) ``` -------------------------------- ### Simplified Setup with `autoscan()` in a Python Project Source: https://morepath.readthedocs.io/latest/configuration.html Demonstrates a simplified setup code when your project is structured as a Python package with a `setup.py` file. `morepath.autoscan()` handles scanning all dependent packages, and `morepath.scan()` can be omitted if your project is properly packaged. ```python if __name__ == '__main__': morepath.autoscan() App.commit() morepath.run(App()) ``` -------------------------------- ### Run Morepath Hello World Example Source: https://morepath.readthedocs.io/latest/_sources/quickstart.rst.txt Execute the 'Hello world!' Morepath application from the command line. ```console $ python hello.py Running <__main__.App object at 0x10f8398d0> Listening on http://127.0.0.1:5000 Press Ctrl-C to stop... ``` -------------------------------- ### Basic Morepath Application Setup Source: https://morepath.readthedocs.io/latest/_sources/configuration.rst.txt This snippet shows a basic Morepath application setup. It includes scanning for Morepath components and running the application. Use this when your application is not yet part of a proper Python project. ```python if __name__ == '__main__': morepath.autoscan() morepath.scan() App.commit() application = App() morepath.run(application) ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://morepath.readthedocs.io/latest/installation.html Sets up a Python virtual environment for Morepath installation. ```bash $ virtualenv morepath_env $ source morepath_env/bin/activate ``` -------------------------------- ### Install WebTest and pytest Source: https://morepath.readthedocs.io/latest/testing.html Install the necessary testing tools using pip. These are typically included if you used the cookiecutter template. ```bash $ pip install webtest pytest ``` -------------------------------- ### Example URL Source: https://morepath.readthedocs.io/latest/web.html Illustrates a basic URL structure. ```text http://example.com/documents/3 ``` -------------------------------- ### Install Development Dependencies Source: https://morepath.readthedocs.io/latest/_sources/developing.rst.txt Install all necessary development tools and dependencies from the 'requirements/develop.txt' file. The '--src src' option checks out dependent projects into the 'src' directory. ```console $ pip install -Ur requirements/develop.txt --src src ``` -------------------------------- ### Install testing tools Source: https://morepath.readthedocs.io/latest/_sources/testing.rst.txt Installs WebTest and pytest using pip. These are recommended tools for testing Morepath projects. ```console $ pip install webtest pytest ``` -------------------------------- ### Install Development Dependencies Source: https://morepath.readthedocs.io/latest/developing.html Install all necessary dependencies and development tools from the requirements/develop.txt file. The --src src option checks out dependent projects into the src directory for local modification. ```bash $ pip install -Ur requirements/develop.txt --src src ``` -------------------------------- ### Install latest Reg development version Source: https://morepath.readthedocs.io/latest/_sources/installation.rst.txt Install the latest development version of the Reg library from its Git repository. ```bash pip install git+git://github.com/morepath/reg.git@master ``` -------------------------------- ### Install Basic Identity Policy Source: https://morepath.readthedocs.io/latest/_sources/security.rst.txt Use the `@App.identity_policy` directive to install an identity policy into a Morepath app. This example shows how to install `BasicAuthIdentityPolicy`. ```python from more.basicauth import BasicAuthIdentityPolicy @App.identity_policy() def get_identity_policy(): return BasicAuthIdentityPolicy() ``` -------------------------------- ### Install Morepath using pip Source: https://morepath.readthedocs.io/latest/_sources/installation.rst.txt Install Morepath into a Python virtual environment using pip. ```bash pip install morepath ``` -------------------------------- ### Install Pre-commit Hook Source: https://morepath.readthedocs.io/latest/_sources/developing.rst.txt Install the pre-commit hook for Black integration. This helps ensure code is formatted correctly before committing. ```console $ pre-commit install ``` -------------------------------- ### Namespace Package Setup Source: https://morepath.readthedocs.io/latest/configuration.html For namespace packages, include the full name in setup.py and ensure the directory structure reflects the namespace. ```python setup( name='my.app' packages=find_packages() namespace_packages=['my'] ... ) ``` -------------------------------- ### Update Setuptools and Pip Source: https://morepath.readthedocs.io/latest/_sources/developing.rst.txt Ensure you have the latest versions of setuptools and pip installed within the active virtual environment. ```console $ pip install -U setuptools pip ``` -------------------------------- ### Run Morepath Project Source: https://morepath.readthedocs.io/latest/installation.html Starts the Morepath application using its console script. ```bash $ myproject-start ``` -------------------------------- ### Simplified Morepath Application Setup in a Python Project Source: https://morepath.readthedocs.io/latest/_sources/configuration.rst.txt This simplified setup is used when your Morepath code is part of a proper Python project. It relies on `morepath.autoscan()` to find dependencies. Ensure your project has a `setup.py` file. ```python if __name__ == '__main__': morepath.autoscan() App.commit() morepath.run(App()) ``` -------------------------------- ### Install latest Morepath development version Source: https://morepath.readthedocs.io/latest/_sources/installation.rst.txt Install the latest development version of Morepath from its Git repository. ```bash pip install git+git://github.com/morepath/morepath.git@master ``` -------------------------------- ### Install Morepath in editable mode Source: https://morepath.readthedocs.io/latest/_sources/installation.rst.txt Install Morepath from a local project directory in editable mode using pip. ```bash pip install --editable . ``` -------------------------------- ### Migrate Manual Setup: Morepath Scan and Autocommit Source: https://morepath.readthedocs.io/latest/changes.html Update code using `morepath.setup` and manual commits to use `morepath.scan` and `morepath.autocommit` for a refactored configuration system. ```python from morepath import setup config = morepath.setup() config.scan(package) config.commit() ``` ```python import morepath morepath.scan(package) morepath.autocommit() ``` -------------------------------- ### Install Bower Component Source: https://morepath.readthedocs.io/latest/more.static.html Installs a Bower JavaScript package like 'jquery' into the 'bower_components' directory. ```bash bower install jquery ``` -------------------------------- ### Install Pre-commit Hook for Black Source: https://morepath.readthedocs.io/latest/developing.html Install the pre-commit hook to automatically format code using Black before each commit. This ensures consistent code style across the project. ```bash $ pre-commit install ``` -------------------------------- ### Example URL for Day Model Source: https://morepath.readthedocs.io/latest/paths_and_linking.html Shows a URL for accessing a specific day using the date converter in the path. ```text /days/20110101 ``` -------------------------------- ### Install Morepath Project with pip Source: https://morepath.readthedocs.io/latest/installation.html Installs a Morepath project in editable mode using pip within its virtual environment. ```bash $ pip install --editable . ``` -------------------------------- ### List Tox Dependencies and Versions Source: https://morepath.readthedocs.io/latest/_sources/developing.rst.txt Use this command to inspect the dependencies and their installed versions within a tox test environment. ```bash $ tox -e freeze ``` -------------------------------- ### Basic ChameleonApp Setup Source: https://morepath.readthedocs.io/latest/_sources/templates.rst.txt Subclass ChameleonApp to enable .pt template file extension. Specify the directory containing your templates using the template_directory directive. ```python from more.chameleon import ChameleonApp class App(ChameleonApp): pass @App.template_directory() def get_template_directory(): return 'templates' ``` -------------------------------- ### Query the App Source: https://morepath.readthedocs.io/latest/testing.html Use the client to make a GET request to the root path ('/') of the application. ```python >>> response = c.get('/') ``` -------------------------------- ### Install Predicates for Dispatch Methods Source: https://morepath.readthedocs.io/latest/changes.html Use the 'predicate' directive to install new predicates for dispatch methods. The first argument must be a reference to the dispatch method, and it allows for custom logic to determine dispatch behavior. ```python @App.predicate(App.get_view, name='model', default=None, index=ClassIndex) def model_predicate(obj): return obj.__class__ ``` -------------------------------- ### Example Path Segment Source: https://morepath.readthedocs.io/latest/views.html Illustrates a URL path segment used for identifying a view. ```text /documents/1/edit ``` -------------------------------- ### Navigate to Morepath Directory Source: https://morepath.readthedocs.io/latest/developing.html Change the current directory to the cloned Morepath repository. This is a prerequisite for subsequent development setup commands. ```bash $ cd morepath ``` -------------------------------- ### Example URL for Records with Date Range Source: https://morepath.readthedocs.io/latest/paths_and_linking.html Illustrates how to construct a URL to query records within a specific date range using encoded date strings. ```text /records?start=20110110&end=20110215 ``` -------------------------------- ### Basic Morepath Application with Models and Views Source: https://morepath.readthedocs.io This snippet demonstrates a basic Morepath application setup. It defines an application class, models, paths for routing, and HTML views for different models. It also includes how to run the application. ```python import morepath class App(morepath.App): pass class Document: def __init__(self, id): self.id = id @App.path(path='') class Root: pass @App.path(path='documents/{id}', model=Document) def get_document(id): return Document(id) # query for doc @App.html(model=Root) def hello_root(self, request): return 'Go to doc' % request.link(Document('foo')) @App.html(model=Document) def hello_doc(self, request): return '

Hello document: %s!

' % self.id if __name__ == '__main__': morepath.run(App()) ``` -------------------------------- ### Navigate to Parent App Source: https://morepath.readthedocs.io/latest/_sources/app_reuse.rst.txt Use `request.app.parent` to get the parent application instance for navigation. ```python request.link(User('faassen'), app=request.app.parent) ``` -------------------------------- ### Serve PNG Image using WebOb FileApp in Morepath Source: https://morepath.readthedocs.io/latest/more.static.html This example demonstrates serving a PNG image using `webob.static.FileApp` within a Morepath view. `FileApp` handles opening the file, determining the MIME type, and setting response headers. ```python from webob import static @App.path(path='') class Image: path = 'image.png' @App.view(model=Image) def view_image(self, request): return request.get_response(static.FileApp(self.path)) ``` -------------------------------- ### Define Document model Source: https://morepath.readthedocs.io/latest/_sources/organizing_your_project.rst.txt Example of a plain Python class for a model, independent of Morepath. ```python class Document: def __init__(self, id, title, content): self.id = id self.title = title self.content = content ``` -------------------------------- ### Equivalent Views Without Grouping Source: https://morepath.readthedocs.io/latest/views.html Illustrates the non-grouped equivalent of the 'with' statement example, showing the repetition of common parameters. ```python @App.view(model=Document) def document_default(self, request): return "default" @App.view(model=Document, name='edit') def document_edit(self, request): return "edit" ``` -------------------------------- ### Define a Framework App with Reusable Views Source: https://morepath.readthedocs.io/latest/_sources/building_large_applications.rst.txt This example illustrates creating a base framework application that defines reusable views for a specific model (Metadata). Other applications can then extend this framework to automatically inherit these views. ```python class Framework(morepath.App): pass class Metadata: def __init__(self, d): self.d = d # metadata dictionary def get_metadata(self): return self.d @Framework.json(model=Metadata, name='metadata') def metadata_view(self, request): return self.get_metadata() ``` -------------------------------- ### Migrate Test Setup: Morepath Commit with App List Source: https://morepath.readthedocs.io/latest/changes.html Adjust test code that previously used `morepath.setup` and `config.commit` to use `morepath.commit` with a list of application objects. ```python import morepath def test_foo(): config = morepath.setup() class App(morepath.App): testing_config = config ... use directives on App ... config.commit() ... do asserts ... ``` ```python import morepath def test_foo(): class App(morepath.App): pass ... use directives on App ... morepath.commit([App]) ... do asserts ... ``` -------------------------------- ### setup.py with Entry Points for Scanning Source: https://morepath.readthedocs.io/latest/_sources/configuration.rst.txt This `setup.py` configuration uses entry points to explicitly declare which package Morepath should scan, allowing the project name ('elephant') to differ from the package name ('my.package'). `morepath` must still be in `install_requires`. ```python setup(name='elephant' ... entry_points={ 'morepath': [ 'scan = my.package' ] }) ``` -------------------------------- ### Configure Console Script Entry Point Source: https://morepath.readthedocs.io/latest/_sources/config_query.rst.txt Set up a console script entry point in setup.py to make the query tool accessible as a command-line command. ```python entry_points={ 'console_scripts': [ 'morepathq = mybigapp.query:query_tool', ] }, ``` -------------------------------- ### Load Settings from YAML File Source: https://morepath.readthedocs.io/latest/_sources/settings.rst.txt Loads settings from a YAML configuration file into a Python dictionary using the `yaml` library. Ensure `pyyaml` is installed. ```yaml jinja2: extensions: - jinja2.ext.autoescape - jinja2.ext.i18n jwtauth: algorithm: ES256 sqlalchemy: url: sqlite:///morepath.db ``` -------------------------------- ### Define Wiki Pages within a User App Source: https://morepath.readthedocs.io/latest/app_reuse.html This example shows an initial approach to integrating wiki functionality directly into a user application, defining paths and views for WikiPage models. ```python from morepath import App class WikiPage: pass # Assume get_wiki_id_for_username, get_wiki, and get_username_for_wiki_id are defined elsewhere def wiki_for_user(username): wiki_id = get_wiki_id_for_username(username) return get_wiki(wiki_id) @App.path(model=WikiPage, path='users/{username}/wiki/{page_id}') def get_wiki_page(username, page_id): return wiki_for_user(username).get_page(page_id) @App.view(model=WikiPage) def wiki_page_default(self, request): return "Wiki Page" ``` -------------------------------- ### Development Server with Automatic Restart Source: https://morepath.readthedocs.io/latest/organizing_your_project.html Integrate Werkzeug's development server for automatic restarts when code changes. Requires Werkzeug to be installed. ```python import morepath from werkzeug.serving import run_simple from .app import App def run(): morepath.autoscan() App.commit() run_simple('localhost', 8080, App(), use_reloader=True) ``` -------------------------------- ### Chameleon Template Example Source: https://morepath.readthedocs.io/latest/_sources/templates.rst.txt A simple Chameleon template file (.pt) that uses variable substitution to display dynamic content. ```html

Hello ${name}!

``` -------------------------------- ### Example of Another Item View Source: https://morepath.readthedocs.io/latest/_sources/views.rst.txt A JSON view for `SomeOtherItem` model, returning its name. This shows another distinct view implementation that can be handled by a composing view. ```python @App.json(model=SomeOtherItem) def some_other_item_default(self, request): return self.name ``` -------------------------------- ### Template Override Setup Source: https://morepath.readthedocs.io/latest/_sources/templates.rst.txt Subclass an existing app and use the template_directory directive to specify a new directory for overriding templates. Morepath searches template directories in application order. ```python class SubApp(App): pass @SubApp.template_directory() def get_override_template_directory(): return 'templates_override' ``` -------------------------------- ### Initialize Local Components Directory Source: https://morepath.readthedocs.io/latest/more.static.html This demonstrates the command-line steps to create a new directory for local components and initialize it with a `bower.json` file using `bower init`. ```bash $ mkdir my_component $ cd my_component $ bower init ``` -------------------------------- ### Running Morepath Application with Autoscan Source: https://morepath.readthedocs.io/latest/_sources/more.static.rst.txt Sets up a function to run the Morepath WSGI application using autoscan for component discovery. This is the recommended way to start the application. ```python from .app import App import morepath def run(): morepath.autoscan() App.commit() wsgi = App() morepath.run(wsgi) ``` -------------------------------- ### Manually Scan a Package Source: https://morepath.readthedocs.io/latest/organizing_your_project.html Use this when automatic scanning fails to pick up a package. Ensure the package is correctly installed in your environment. ```python import mysterious_package morepath.scan(mysterious_package) ``` -------------------------------- ### Implement Wiki Paths in User App Source: https://morepath.readthedocs.io/latest/_sources/app_reuse.rst.txt Example of implementing wiki page paths directly within a user application. This approach can lead to issues with app separation and path complexity. ```python def wiki_for_user(username): wiki_id = get_wiki_id_for_username(username) return get_wiki(wiki_id) @App.path(model=WikiPage, path='users/{username}/wiki/{page_id}') def get_wiki_page(username, page_id): return wiki_for_user(username).get_page(page_id) @App.view(model=WikiPage) def wiki_page_default(self, request): return "Wiki Page" ``` -------------------------------- ### Register Path and View for User Model Source: https://morepath.readthedocs.io/latest/_sources/app_reuse.rst.txt Associate a model with a URL path and define a default view for it. This example registers the User model under '/users/{username}'. ```python @App.path(model=User, path='users/{username}') def get_user(username): return query_for_user(username) @App.view(model=User) def render_user(self, request): return "User: %s" % self.username ``` -------------------------------- ### Load Settings from YAML Config File Source: https://morepath.readthedocs.io/latest/settings.html Load settings from a YAML file into a Python dictionary using `yaml.safe_load()`. Ensure `pyyaml` is installed. ```yaml # Config file for Morepath in YAML format chameleon: debug: true jinja2: auto_reload: false autoescape: true extensions: - jinja2.ext.autoescape - jinja2.ext.i18n jwtauth: algorithm: ES256 leeway: 20 public_key: "MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBWcJwPEAnS/k4kFgUhxNF7J0SQQhZG+nNgy\ +/mXwhQ5PZIUmId1a1TjkNXiKzv6DpttBqduHbz/V0EtH+QfWy0B4BhZ5MnTyDGjcz1DQqK dexebhzobbhSIZjpYd5aU48o9rXp/OnAnrajddpGsJ0bNf4rtMLBqFYJN6LOslAB7xTBRg=" sqlalchemy: url: 'sqlite:///morepath.db' transaction: attempts: 2 ``` ```python import yaml with open('settings.yml') as config: settings_dict = yaml.safe_load(config) ``` -------------------------------- ### Run Morepath Application Source: https://morepath.readthedocs.io/latest/organizing_your_project.html This snippet defines the `run()` function in `run.py`, which is responsible for setting up and starting the Morepath application. It includes steps for autoscan, committing the app configuration, and running the WSGI server. ```python from .app import App def run(): morepath.autoscan() App.commit() morepath.run(App()) ``` -------------------------------- ### View Tox Testenv Dependencies Source: https://morepath.readthedocs.io/latest/developing.html Use 'tox -e freeze' to inspect the dependencies and their versions installed by tox in a test environment. ```bash $ tox -e freeze ``` -------------------------------- ### Instantiate App and Client Source: https://morepath.readthedocs.io/latest/testing.html Create instances of the application under test and the WebTest client. ```python >>> c = Client(App()) ``` -------------------------------- ### Route Tree Structure Example Source: https://morepath.readthedocs.io/latest/internals/traject.html Illustrates how URL routes are transformed into a hierarchical tree structure for efficient lookup. This structure helps in resolving paths by traversing the tree. ```text a/b a/b/c a/d ``` ```text a b b c d ``` -------------------------------- ### Configure and Run Morepath Application Source: https://morepath.readthedocs.io/latest/more.static.html Set up the `run.py` module to configure and run your Morepath WSGI application. This involves scanning for Morepath configurations, committing application changes, and starting the WSGI server. ```python from .app import App import morepath def run(): morepath.autoscan() App.commit() wsgi = App() morepath.run(wsgi) ``` -------------------------------- ### `_class _morepath.autosetup.DependencyMap` Source: https://morepath.readthedocs.io/latest/internals/autosetup.html A registry that tracks dependencies between distributions. Used by `morepath_packages()` to find installed Python distributions that depend on Morepath, directly or indirectly. ```APIDOC ## `_class _morepath.autosetup.DependencyMap` ### Description A registry that tracks dependencies between distributions. Used by `morepath_packages()` to find installed Python distributions that depend on Morepath, directly or indirectly. ``` -------------------------------- ### Explicitly Commit App Configuration Source: https://morepath.readthedocs.io/latest/_sources/configuration.rst.txt Run configuration steps explicitly before starting the WSGI server. This ensures configuration errors are reported immediately during startup. ```python if __name__ == '__main__': App.commit() application = App() morepath.run(application) ``` -------------------------------- ### New Way: Mounting App During Instantiation Source: https://morepath.readthedocs.io/latest/changes.html Mounting is now handled during the instantiation of the application class. ```python mounted_wiki_app = wiki_app(wiki_id=3) ``` -------------------------------- ### Define a Tweaked Wiki Application Source: https://morepath.readthedocs.io/latest/_sources/building_large_applications.rst.txt This example demonstrates how to create a customized version of an existing application (WikiApp) by subclassing it and adding new views. This allows for specific modifications without altering the original application. ```python from myproject.wiki.app import WikiApp class TweakedWikiApp(WikiApp): pass # some kind of tweak @TweakedWikiApp.json(model=WikiPage, name='extra_info') def page_extra_info(self, request): ... ``` -------------------------------- ### Configure Identity Policy Settings Source: https://morepath.readthedocs.io/latest/_sources/security.rst.txt The `@App.identity_policy` decorator can accept settings. This example demonstrates how to define settings for the policy and pass them to a custom `CustomIdentityPolicy`. ```python @App.setting_section(section="policy") def get_policy_settings(): return {'encryption_key': 'secret'} @App.identity_policy() def get_identity_policy(settings): policy_settings = settings.policy.__dict__.copy() return CustomIdentityPolicy(**policy_settings) ``` -------------------------------- ### Build HTML Documentation with Make Source: https://morepath.readthedocs.io/latest/developing.html Build HTML documentation using the Make utility. ```bash $ cd doc $ make html ``` ```bash $ make -C doc html ``` -------------------------------- ### Create Python 3 Virtual Environment Source: https://morepath.readthedocs.io/latest/_sources/developing.rst.txt Create a new virtual environment named 'env/py3' using Python 3 within the Morepath directory. Ensure virtualenv is installed. ```console $ virtualenv -p python3 env/py3 ``` -------------------------------- ### Handle GET Request for Document Collection Source: https://morepath.readthedocs.io/latest/_sources/rest.rst.txt Defines the JSON response for a GET request to a DocumentCollection, returning a list of document IDs. ```python @App.json(model=DocumentCollection) def document_collection_default(self, request): return { 'type': 'document_collection', 'ids': [doc.id for doc in self.documents] } ``` -------------------------------- ### setup.py for a Morepath Project Source: https://morepath.readthedocs.io/latest/_sources/configuration.rst.txt This `setup.py` configuration is for a Morepath project. It includes `morepath` and `more.jinja2` in `install_requires`, ensuring Morepath can scan your project and its dependencies. ```python setup(name='myapp', packages=find_packages(), install_requires=[ 'more.jinja2', 'morepath' ]) ``` -------------------------------- ### Expose a Model using URL Query Parameters Source: https://morepath.readthedocs.io/latest/_sources/paths_and_linking.rst.txt Publish a Document model using a path without variables, where arguments to the path function are treated as URL query parameters. This example shows exposing documents via '?name=foo'. ```python @App.path(model=Document, path='documents') def get_document(name): return query_document_by_name(name) ``` -------------------------------- ### `morepath.autosetup.get_module_name(_distribution_)` Source: https://morepath.readthedocs.io/latest/internals/autosetup.html Determines the module name to import from the given distribution. If an entry point named `scan` is found in the group `morepath`, it’s value is used. If not, the project name is used. See `morepath.autoscan()` for details and an example. ```APIDOC ## `morepath.autosetup.get_module_name(_distribution_)` ### Description Determines the module name to import from the given distribution. If an entry point named `scan` is found in the group `morepath`, it’s value is used. If not, the project name is used. See `morepath.autoscan()` for details and an example. ### Parameters #### Path Parameters - **_distribution_** (importlib.Distribution) - Required - The distribution to determine the module name from. ``` -------------------------------- ### Example of a Specific Item View Source: https://morepath.readthedocs.io/latest/_sources/views.rst.txt A JSON view for a `ParticularItem` model, returning a dictionary with its ID. This demonstrates a specific view that can be composed by a more generic collection view. ```python @App.json(model=ParticularItem) def particular_item_default(self, request): return {'id': self.id} ``` -------------------------------- ### Using request.view with Predicates Source: https://morepath.readthedocs.io/latest/views.html This example shows how to use `request.view()` with additional predicates, specifically `name` and `request_method`, to select a view that matches these criteria. This allows for more specific view resolution beyond just the model. ```python request.view(item, name="edit", request_method="POST") ``` -------------------------------- ### Build HTML Documentation Source: https://morepath.readthedocs.io/latest/developing.html Generate HTML documentation for Morepath. ```bash $ sphinx-build doc doc/build/html ``` -------------------------------- ### Setup.py Configuration for Namespace Packages Source: https://morepath.readthedocs.io/latest/_sources/organizing_your_project.rst.txt Configure your setup.py to declare namespace packages and define console script entry points for your Morepath application. ```python setup(name='myproject.core', packages=find_packages(), namespace_packages=['myproject'], install_requires=[ 'morepath' ], entry_points={ 'console_scripts': [ 'myproject.core-start = myproject.core.run:run' ] }) ``` -------------------------------- ### Scan using Entry Points Source: https://morepath.readthedocs.io/latest/configuration.html Explicitly declare packages to be scanned by Morepath using entry points in setup.py if the project name differs from the package name. ```python setup(name='elephant' ... entry_points={ 'morepath': [ 'scan = my.package' ] } ) ``` -------------------------------- ### Define Permission Rule for All Documents (View) Source: https://morepath.readthedocs.io/latest/_sources/security.rst.txt Register a generic permission rule for a specific permission class and model type. This example grants view permission to everyone for any Document. ```python @App.permission_rule(model=Document, permission=ViewPermission) def document_view_permission(identity, model, permission) return True ``` -------------------------------- ### Query Path Directives Source: https://morepath.readthedocs.io/latest/config_query.html Use the `morepathq` tool to query for 'path' directives, filtering by a specific model. This example shows how to find path directives associated with `mybigapp.model.Foo`. ```bash $ morepathq path model=mybigapp.model.Foo App: File ".../path.py", line 8 @App.path(model=Foo, path="/foo") ``` -------------------------------- ### Hello World Application in Morepath Source: https://morepath.readthedocs.io/latest/_sources/quickstart.rst.txt A minimal 'Hello world!' application using Morepath. Save this as hello.py and run it with Python. ```python import morepath class App(morepath.App): pass @App.path('') class Root(object): pass @App.view(model=Root) def hello_world(self, request): return 'Hello world!' if __name__ == '__main__': import morepath.run morepath.run(App()) ``` -------------------------------- ### PredicateRegistry Source: https://morepath.readthedocs.io/latest/extension_api.html Manages predicates for dispatch functions, including sorting and installation. ```APIDOC ## class morepath.directive.PredicateRegistry(app_class) A registry of what predicates are registered for which functions. It also keeps track of how predicates are to be ordered. ### get_predicates(dispatch) Create Reg predicates. This creates `reg.Predicate` objects for a particular dispatch function. Uses `PredicateRegistry.sorted_predicate_infos()` to sort the predicate infos. **Parameters:** * **dispatch** – the dispatch function to create the predicates for. **Returns:** a list of `reg.Predicate` instances in the correct order. ### install_predicates() Install the predicates with reg. This should be called during configuration once all predicates and fallbacks are known. Uses `PredicateRegistry.get_predicates()` to get out the predicates in the correct order. ### register_predicate(func, dispatch, name, default, index, before, after) Register a predicate for installation into the reg registry. See `morepath.App.predicate()` for details. **Parameters:** * **func** – the function that implements the predicate. * **dispatch** – the dispatch function to register the predicate on. * **name** – name of the predicate. * **default** – default value. * **index** – index to use. * **before** – predicate function to have priority over. * **after** – predicate function that has priority over this one. ### register_predicate_fallback(dispatch, func, fallback_func) Register a predicate fallback for installation into reg registry. See `morepath.App.predicate_fallback()` for details. **Parameters:** * **dispatch** – the dispatch function to register fallback on. * **func** – the predicate function to register fallback for. * **fallback_func** – the fallback function. ### sorted_predicate_infos(dispatch) Topologically sort predicate infos for a dispatch function. **Parameters:** * **dispatch** – the dispatch function to sort for. **Returns:** a list of sorted `PredicateInfo` instances. ``` -------------------------------- ### Create and Populate User Database Source: https://morepath.readthedocs.io/latest/_sources/quickstart.rst.txt Initialize a dictionary to store users and a function to add them. Populate with sample users. ```python users = {} def add_user(user): users[user.username] = user faassen = User('faassen', 'Martijn Faassen', 'faassen@startifact.com') bob = User('bob', 'Bob Bobsled', 'bob@example.com') add_user(faassen) add_user(bob) ``` -------------------------------- ### Navigate to Mounted App by Path and Keyword Arguments Source: https://morepath.readthedocs.io/latest/_sources/app_reuse.rst.txt Use `request.app.child` with a path string and keyword arguments to specify the mounted application. ```python wiki_app = request.app.child('users/{username}/wiki', username='faassen') ``` -------------------------------- ### Run Documentation Doctests with Make Source: https://morepath.readthedocs.io/latest/developing.html Run documentation doctests using the Make utility. ```bash (py3) $ cd doc (py3) $ make doctest ``` ```bash (py3) $ make -C doc doctest ``` -------------------------------- ### Example JSON Structure Source: https://morepath.readthedocs.io/latest/web.html A typical JSON object representing a resource with various data types. ```json { "id": "foo_barson", "name": "Foo Barson", "occupation": "Carpenter", "level": 34 "friends": ["http://example.com/people/qux_quxson", "http://example.com/people/one_twonson"] } ``` -------------------------------- ### `morepath.autosetup.import_package(_distribution_)` Source: https://morepath.readthedocs.io/latest/internals/autosetup.html Takes a importlib.Distribution and loads the module contained in it, if it matches the rules layed out in `morepath.autoscan()`. ```APIDOC ## `morepath.autosetup.import_package(_distribution_)` ### Description Takes a importlib.Distribution and loads the module contained in it, if it matches the rules layed out in `morepath.autoscan()`. ### Parameters #### Path Parameters - **_distribution_** (importlib.Distribution) - Required - The distribution to import. ``` -------------------------------- ### Navigate to Mounted App by Class and Keyword Arguments Source: https://morepath.readthedocs.io/latest/_sources/app_reuse.rst.txt Use `request.app.child` with the application class and keyword arguments to specify the mounted application. ```python wiki_app = request.app.child(WikiApp, username='faassen') ``` -------------------------------- ### Get Document Collection Source: https://morepath.readthedocs.io/latest/_sources/rest.rst.txt Retrieves a JSON representation of the document collection, including the IDs of all documents. ```APIDOC ## GET /documents ### Description Retrieves a JSON structure containing the IDs of all documents in the collection. ### Method GET ### Endpoint /documents ### Response #### Success Response (200) - **type** (string) - Indicates the type of the resource, e.g., "document_collection". - **ids** (array of strings) - A list of document IDs. ### Response Example ```json { "type": "document_collection", "ids": ["doc1", "doc2"] } ``` ``` -------------------------------- ### setup.py with Morepath Dependency Source: https://morepath.readthedocs.io/latest/_sources/configuration.rst.txt This `setup.py` configuration ensures that `morepath` is listed in `install_requires`. This is crucial for Morepath to automatically scan your package and its dependencies. ```python setup(name='myapp' ... install_requires=[ 'morepath' ]) ``` -------------------------------- ### Mounting a Sub-App with Customization Source: https://morepath.readthedocs.io/latest/_sources/building_large_applications.rst.txt Mount a sub-application (e.g., a wiki) into a core application, specifying the path and providing a factory function to instantiate the sub-app with necessary variables. This allows for dynamic mounting and configuration. ```python @CoreApp.mount(path='{user_name}/{repository_name}/wiki', app=ShinyNewWikiApp, variables=variables) def mount_wiki(user_name, repository_name): return ShinyNewWikiApp(get_wiki_id(user_name, repository_name)) ``` -------------------------------- ### View Predicate Example Source: https://morepath.readthedocs.io/latest/web.html This directive defines a view that only matches when the model is MyCollection and the request method is POST. ```python @App.view(model=MyCollection, request_method='POST') def add_to_collection(self, request): ... ``` -------------------------------- ### Run Waitress with Prepared WSGI App Source: https://morepath.readthedocs.io/latest/organizing_your_project.html Serve a pre-configured WSGI application instance using `waitress-serve`. ```bash $ waitress-serve myproject.wsgi:prepared_app ``` -------------------------------- ### URL with Parameters Source: https://morepath.readthedocs.io/latest/web.html Demonstrates a URL including query parameters. ```text http://example.com/documents/3?expand=1&highlight=foo ``` -------------------------------- ### caller_package Source: https://morepath.readthedocs.io/latest/_sources/internals/autosetup.rst.txt Returns the package of the caller of the current function. This helps in identifying the package context for automated setup routines. ```APIDOC ## caller_package ### Description Returns the package of the caller of the current function. This helps in identifying the package context for automated setup routines. ### Function Signature `caller_package() -> package` ``` -------------------------------- ### Initialize Local Bower Component Source: https://morepath.readthedocs.io/latest/_sources/more.static.rst.txt Create a new directory for local components and initialize it with a bower.json file using the 'bower init' command. ```bash $ mkdir my_component $ cd my_component $ bower init ``` -------------------------------- ### DependencyMap Source: https://morepath.readthedocs.io/latest/_sources/internals/autosetup.rst.txt Represents a dependency map for managing package dependencies during setup. It provides methods to add and retrieve dependencies. ```APIDOC ## DependencyMap ### Description Represents a dependency map for managing package dependencies during setup. It provides methods to add and retrieve dependencies. ### Methods - **add_dependency(dependency_name: str, package_name: str)**: Adds a dependency relationship. - **get_dependencies(package_name: str)**: Retrieves the dependencies for a given package. ``` -------------------------------- ### Require Waitress in setup.py Source: https://morepath.readthedocs.io/latest/_sources/organizing_your_project.rst.txt Add 'waitress' to install_requires in setup.py to include it as a project dependency. ```python ... install_requires=[ 'morepath', 'waitress' ], ... ``` -------------------------------- ### Replace morepath.autosetup with autoscan Source: https://morepath.readthedocs.io/latest/changes.html Use `morepath.autoscan()` instead of `morepath.autosetup()`. The `App.commit()` method is now optional or can rely on automatic committing during the first request. ```python morepath.autosetup() morepath.run(App()) ``` ```python morepath.autoscan() App.commit() # optional morepath.run(App()) ``` -------------------------------- ### Define a Permission Class Source: https://morepath.readthedocs.io/latest/superpowers.html Permissions are defined as simple Python classes. This example shows the basic structure for an 'Edit' permission. ```python class Edit: pass ``` -------------------------------- ### Instantiate a Standalone Wiki App Source: https://morepath.readthedocs.io/latest/app_reuse.html Shows how to create an instance of the `WikiApp` with a specific `wiki_id`. ```python app = WikiApp(3) ``` -------------------------------- ### Old Way: Instantiating App Source: https://morepath.readthedocs.io/latest/changes.html Before Morepath 0.4, applications were created by instantiating morepath.App directly. ```python app = morepath.App() ``` -------------------------------- ### Access Request Headers Source: https://morepath.readthedocs.io/latest/_sources/web.rst.txt HTTP headers are accessible on the request object as a dictionary-like attribute. This example shows how to access the 'Content-Type' header. ```python request.headers['Content-Type'] ``` -------------------------------- ### Define a Basic Tween Factory Source: https://morepath.readthedocs.io/latest/_sources/tweens.rst.txt This is a basic example of a tween factory that wraps a handler. It prints 'Enter' before calling the handler and 'Exit' after. ```python def make_tween(app, handler): def my_tween(request): print "Enter" response = handler(request) print "Exit" return response return my_tween ``` -------------------------------- ### Navigate to Mounted App by Instance Source: https://morepath.readthedocs.io/latest/_sources/app_reuse.rst.txt Use `request.app.child` with an application instance to navigate to a mounted child application. ```python wiki_app = request.app.child(WikiApp(3)) ``` -------------------------------- ### import_package Source: https://morepath.readthedocs.io/latest/_sources/internals/autosetup.rst.txt Imports a package and returns its module object. This function is used to automate the setup and configuration of packages within the Morepath framework. ```APIDOC ## import_package ### Description Imports a package and returns its module object. This function is used to automate the setup and configuration of packages within the Morepath framework. ### Function Signature `import_package(package_name: str)` ### Parameters #### Path Parameters - **package_name** (str) - Required - The name of the package to import. ``` -------------------------------- ### Project Name Matches Package Name Source: https://morepath.readthedocs.io/latest/configuration.html When using the naming convention for scanning, the project name in setup.py must match the Python package name. ```python setup( name='myapp', packages=find_packages(), ... ) ``` -------------------------------- ### New Way: App Class for Configuration, Instance for WSGI Source: https://morepath.readthedocs.io/latest/changes.html Morepath 0.4 separates configuration (class) from WSGI (instance). ```python class app(morepath.App): pass # configuration @app.path(...) ... # wsgi morepath.run(app()) ``` -------------------------------- ### Initialize App Settings from Dictionary Source: https://morepath.readthedocs.io/latest/_sources/settings.rst.txt Registers a dictionary of settings with the application using `App.init_settings` before committing the app. This allows pre-filling settings from external sources. ```python App.init_settings(settings_dict) morepath.commit(App) app = App() ``` -------------------------------- ### Redirect to another URL in Morepath Source: https://morepath.readthedocs.io/latest/quickstart.html Use `morepath.redirect()` to redirect to another URL. This example redirects to a link generated for a 'other' name on the current model. ```python from morepath import App from .models import User @App.view(model=User, name='extra') def redirecting(self, request): return morepath.redirect(request.link(self, 'other')) ``` -------------------------------- ### Composing JSON Results with request.view Source: https://morepath.readthedocs.io/latest/_sources/views.rst.txt Use request.view to construct composed JSON results. This example shows retrieving views based on a 'name' attribute. ```python request.view(item, name="edit", request_method="POST") ``` -------------------------------- ### Manual Package Loading in Morepath Source: https://morepath.readthedocs.io/latest/changes.html Use this method when Morepath cannot automatically load packages due to differences between setup.py names and module names. It requires explicit scanning of the target module. ```python import morepath import myapp config = morepath.setup() config.scan(myapp) config.commit() ``` -------------------------------- ### Define a Model for Linking Source: https://morepath.readthedocs.io/latest/paths_and_linking.html Define a model class and a path function to retrieve instances of that model. This setup is necessary for generating links to model objects. ```python class Document: def __init__(self, name): self.name = name @App.path(model=Document, path='documents/{name}') def get_document(name): return query_document_by_name(name) ``` -------------------------------- ### Expose a Model Class to a Simple Path Source: https://morepath.readthedocs.io/latest/_sources/paths_and_linking.rst.txt Publish a model class (Overview) to a static path ('overview') without any variables. A default view is provided to display content at the URL. ```python class Overview: pass @App.path(model=Overview, path='overview') def get_overview(): return Overview() @App.view(model=Overview) def overview_default(self, request): return "Overview" ``` -------------------------------- ### Query All Views Source: https://morepath.readthedocs.io/latest/config_query.html Use the `morepathq` command-line tool to query for all 'view' directives. This will display the application, file path, and line number where each view is defined. ```bash $ morepathq view App: File ".../somemodule.py", line 4 @App.html(model=Foo) File ".../anothermodule.py", line 8 @App.json(model=Bar) ``` -------------------------------- ### Build HTML Documentation Source: https://morepath.readthedocs.io/latest/_sources/developing.rst.txt Generate the HTML version of the documentation. The output will be in 'doc/build/html'. This can be done via sphinx-build or make. ```console $ sphinx-build doc doc/build/html ``` ```console $ cd doc $ make html ``` ```console $ make -C doc html ``` -------------------------------- ### Import Application Source: https://morepath.readthedocs.io/latest/testing.html Import the Morepath application that needs to be tested. Assumes the application is saved in 'hello.py'. ```python >>> from hello import App ``` -------------------------------- ### Run Gunicorn with Prepared WSGI App Source: https://morepath.readthedocs.io/latest/organizing_your_project.html Serve a pre-configured WSGI application instance using `gunicorn`. ```bash $ gunicorn -w 4 myproject.wsgi:prepared_app ``` -------------------------------- ### `DependencyMap.load()` Source: https://morepath.readthedocs.io/latest/internals/autosetup.html Fill the registry with dependency information. ```APIDOC ## `DependencyMap.load()` ### Description Fill the registry with dependency information. ``` -------------------------------- ### Verify Password-Based Identity Source: https://morepath.readthedocs.io/latest/security.html Use this snippet when your identity policy relies on verifying a username and password combination. The `identity` object's attributes depend on the installed policy. ```python @App.verify_identity() def verify_identity(identity): return user_has_password(identity.username, identity.password) ``` -------------------------------- ### `morepath.autosetup.caller_package(_level =2_)` Source: https://morepath.readthedocs.io/latest/internals/autosetup.html Give package where calling function is defined. ```APIDOC ## `morepath.autosetup.caller_package(_level =2_)` ### Description Give package where calling function is defined. ### Parameters #### Path Parameters - **_level_** (int) - Optional - levels deep to look up the stack frame. Defaults to 2. ### Returns - a Python module (representing the `__init__.py` of a package) ``` -------------------------------- ### morepath.autoscan Source: https://morepath.readthedocs.io/latest/api.html Automatically loads Morepath configuration from packages based on setup.py information and entry points. This function facilitates the discovery of Morepath configurations across installed packages. ```APIDOC ## `morepath.autoscan` ### Description Automatically load Morepath configuration from packages. Morepath configuration consists of decorator calls on `App` instances, i.e. `@App.view()` and `@App.path()`. This function tries to load needed Morepath configuration from all packages automatically. This only works if: > * The package is made available using a `setup.py` file. > * The package or a dependency of the package includes `morepath` in the `install_requires` list of the `setup.py` file. > * The `setup.py` name is the same as the name of the distributed package or module. For example: if the module inside the package is named `myapp` the package must be named `myapp` as well (not `my-app` or `MyApp`). > If the `setup.py` name differs from the package name, it’s possible to specify the module morepath should scan using entry points: ``` setup(name='some-package', ... install_requires=[ 'setuptools', 'morepath' ], entry_points={ 'morepath': [ 'scan = somepackage', ] }) ``` ### Parameters * **ignore** - Optional. Defaults to `['.test', '.tests']`. ``` -------------------------------- ### Old Way: Mounting App with mount() Source: https://morepath.readthedocs.io/latest/changes.html Manual mounting of an application with variables used the special mount() method. ```python mounted_wiki_app = wiki_app.mount(wiki_id=3) ``` -------------------------------- ### Extend WikiApp with Custom View Source: https://morepath.readthedocs.io/latest/building_large_applications.html Extend an existing application class to add custom views or modify behavior. This example adds an 'extra_info' JSON view to a 'TweakedWikiApp'. ```python from myproject.wiki.app import WikiApp class TweakedWikiApp(WikiApp): pass # some kind of tweak @TweakedWikiApp.json(model=WikiPage, name='extra_info') def page_extra_info(self, request): ... ``` -------------------------------- ### Path with Explicit Date Converter Source: https://morepath.readthedocs.io/latest/_sources/paths_and_linking.rst.txt Define a path with a specific converter for a path variable using the 'converters' dictionary. This example uses a date converter for the 'd' path variable. ```python from datetime import date class Day: def __init__(self, d): self.d = d def date_converter(s): # Placeholder for date conversion logic return date.fromisoformat(s) @App.path(model=Day, path='days/{d}', converters=dict(d=date_converter)) def get_day(d): return Day(d) ``` -------------------------------- ### Define and register a setting Source: https://morepath.readthedocs.io/latest/_sources/implementation.rst.txt Use morepath.App.setting to declare and register application-wide settings. ```python import morepath class MyApp(morepath.App): @morepath.App.setting(key='my_setting') def get_my_setting(self): return 'my_value' ``` -------------------------------- ### Old Way: App as Configuration and WSGI Object Source: https://morepath.readthedocs.io/latest/changes.html In older versions, the application object served as both the configuration point and the WSGI object. ```python app = morepath.App() # configuration @app.path(...) ... # wsgi morepath.run(app) ``` -------------------------------- ### Default View Lookup Source: https://morepath.readthedocs.io/latest/compared.html This example shows how Morepath uses a default view when no specific path segment is supplied. For a '/document' path, the default view for the document model is looked up. ```text /document ``` -------------------------------- ### Verify User Identity Source: https://morepath.readthedocs.io/latest/_sources/security.rst.txt Implement the `verify_identity` function using the `@App.verify_identity` directive to check if a claimed identity is legitimate. This example assumes a `user_has_password` function exists to validate credentials. ```python @App.verify_identity() def verify_identity(identity): return user_has_password(identity.username, identity.password) ``` -------------------------------- ### Mounting a Sub-Application Source: https://morepath.readthedocs.io/latest/building_large_applications.html Use the mount directive to swap in a new sub-application, like a different wiki implementation. This involves specifying the path, the new app, and any necessary variables. ```python from morepath import redirect @CoreApp.mount(path='{user_name}/{repository_name}/wiki', app=ShinyNewWikiApp, variables=variables) def mount_wiki(user_name, repository_name): return ShinyNewWikiApp(get_wiki_id(user_name, repository_name)) ``` -------------------------------- ### Handling Different Request Methods for a View Source: https://morepath.readthedocs.io/latest/_sources/views.rst.txt Define separate view functions for the same model and name, distinguished by their `request_method`. This allows handling GET and POST requests differently for the same endpoint. ```python @App.view(model=Document, name='edit', request_method='GET') def document_edit_get(self, request): return "get edit view on model: %s" % self.id @App.view(model=Document, name='edit', request_method='POST') def document_edit_post(self, request): return "post edit view on model: %s" % self.id ``` -------------------------------- ### Handling Specific Request Methods Source: https://morepath.readthedocs.io/latest/_sources/views.rst.txt By default, views handle GET requests. Use the `request_method` parameter in the `@App.view` decorator to specify which HTTP methods a view should respond to, such as 'POST'. ```python @App.view(model=Document, name='edit', request_method='POST') def document_edit(self, request): return "edit view on model: %s" % self.id ``` -------------------------------- ### Path with custom date converters Source: https://morepath.readthedocs.io/latest/_sources/paths_and_linking.rst.txt Define a path for a Records model that uses custom converters for 'start' and 'end' date parameters. These parameters will be decoded from strings to date objects. ```python @App.path(model=Records, path='records', converters=dict(start=date_converter, end=date_converter)) def get_records(start, end): return Records(start, end) ``` -------------------------------- ### Navigate to Morepath Directory Source: https://morepath.readthedocs.io/latest/_sources/developing.rst.txt Change the current directory to the cloned Morepath project folder. ```console $ cd morepath ``` -------------------------------- ### New Way: Extending App with Subclassing Source: https://morepath.readthedocs.io/latest/changes.html Application extension is now achieved through standard Python subclassing. ```python class sub_app(core_app): pass ```